Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the occurrence of one or more substrings in a string

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

like image 636
Pig Avatar asked Mar 10 '17 19:03

Pig


Video Answer


2 Answers

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))
like image 157
JimB Avatar answered Oct 20 '22 22:10

JimB


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.

like image 41
squiguy Avatar answered Oct 20 '22 22:10

squiguy