1 回答

TA貢獻1744條經驗 獲得超4個贊
我真的只看到用 Go 做這件事的幾種方法。
最直接的方法是只匹配一側,然后做一些后正則表達式邏輯:
https://play.golang.org/p/1_4fi-4kMhi
content := []byte("dog dog, cat cats; ")
re := regexp.MustCompile(`(?:[ ,;]|^)(cat|dog)`)
matches := re.FindAllIndex(content, -1)
for _, match := range matches {
next := string(content[match[1]])
if next == "," || next == " " || next == ";" {
fmt.Println(string(content[match[0]:match[1]+1]))
}
}
另一種方法是復制任何分隔符:
https://play.golang.org/p/krDlmHfepA1
content := []byte("dog dog, cat cats; ")
re := regexp.MustCompile(`([ ,;])`)
content = re.ReplaceAll(content, []byte("$1$1"))
fmt.Println(string(content))
re = regexp.MustCompile(`(?:[ ,;]|^)(cat|dog)(?:[ ,;]|$)`)
matches := re.FindAllSubmatch(content, -1)
for _, match := range matches {
for _, submatch := range match[1:] {
fmt.Println(string(submatch))
}
}
- 1 回答
- 0 關注
- 116 瀏覽
添加回答
舉報