I know that for counting the occurrence of one substring I can use "strings.Count(, )". What if I want to count the number of occurrences of substring1 OR substring2? Is there a more elegant way than writing another new line with strings.count()?
Use a regular expression:
https://play.golang.org/p/xMsHIYKtkQ
aORb := regexp.MustCompile("A|B")
matches := aORb.FindAllStringIndex("A B C B A", -1)
fmt.Println(len(matches))
                        Another way to do substring matching is with the suffixarray package. Here is an example of matching multiple patterns:
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))
}
You can also match a single substring with the Lookup function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With