Counting the occurrence of one or more substrings in a string

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.


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))