我知道如果要计算一个子字符串出现的次数,可以使用 "strings.Count(, )"。但如果我想计算子字符串1或子字符串2出现的次数呢?有没有比写另一行 strings.count() 更优雅的方式?
使用正则表达式:
https://play.golang.org/p/xMsHIYKtkQ
aORb := regexp.MustCompile("A|B")
matches := aORb.FindAllStringIndex("A B C B A", -1)
fmt.Println(len(matches))
另一种进行子字符串匹配的方法是使用suffixarray包。以下是匹配多个模式的示例:
package main
import (
"fmt"
"index/suffixarray"
"regexp"
)
func main() {
r := regexp.MustCompile("an")
index := suffixarray.New([]byte("banana"))
results := index.FindAllIndex(r, -1)
fmt.Println(len(results))
}
Regexp.FindStringIndex
在循环中匹配连续的子字符串:func countMatches(s string, re *regexp.Regexp) int {
total := 0
for start := 0; start < len(s); {
remaining := s[start:] // slicing the string is cheap
loc := re.FindStringIndex(remaining)
if loc == nil {
break
}
// loc[0] is the start index of the match,
// loc[1] is the end index (exclusive)
start += loc[1]
total++
}
return total
}
func main() {
s := "abracadabra"
fmt.Println(countMatches(s, regexp.MustCompile(`a|b`)))
}