/
find.go
39 lines (34 loc) · 856 Bytes
/
find.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package stringutil
// FindUnquoted returns the indexes of the instance of v in s, or empty slice if v is not present in s.
// It ignores v present inside quoted runs.
func FindUnquoted(s string, v rune, quote rune) []int {
escaped := false
quoted := false
indexes := make([]int, 0)
quotedIndexes := make([]int, 0)
for i := 0; i < len(s); i++ {
switch rune(s[i]) {
case escape:
escaped = !escaped // escape can escape itself.
case quote:
if escaped {
escaped = false
continue
}
quoted = !quoted
if !quoted {
quotedIndexes = quotedIndexes[:0] // drop possible indices inside quoted segment
}
case v:
escaped = false
if quoted {
quotedIndexes = append(quotedIndexes, i)
} else {
indexes = append(indexes, i)
}
default:
escaped = false
}
}
return append(indexes, quotedIndexes...)
}