-
Notifications
You must be signed in to change notification settings - Fork 218
/
Copy pathutil.go
47 lines (39 loc) · 906 Bytes
/
util.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
40
41
42
43
44
45
46
47
package util
import "regexp"
// RegexpSplit split slice str into substrings separated by the expression and
// return a slice
//
// This function consistent with Python's re.split function.
func RegexpSplit(re *regexp.Regexp, s string, n int) []string {
if n == 0 {
return nil
}
if len(re.String()) > 0 && len(s) == 0 {
return []string{""}
}
var matches [][]int
if len(re.SubexpNames()) > 1 {
matches = re.FindAllStringSubmatchIndex(s, n)
} else {
matches = re.FindAllStringIndex(s, n)
}
strs := make([]string, 0, len(matches))
begin, end := 0, 0
for _, match := range matches {
if n > 0 && len(strs) >= n-1 {
break
}
end = match[0]
if match[1] != 0 {
strs = append(strs, s[begin:end])
}
begin = match[1]
if len(re.SubexpNames()) > 1 {
strs = append(strs, s[match[0]:match[1]])
}
}
if end != len(s) {
strs = append(strs, s[begin:])
}
return strs
}