Go: Find all substrings matching a regexp

Use the FindAllString method to find the text of all matches. A return value of nil indicates no match.

The method takes an integer argument n; if n >= 0, the function returns at most n matches.

re := regexp.MustCompile(`a.`)
fmt.Printf("%q\n", re.FindAllString("paranormal", -1)) // ["ar" "an" "al"]
fmt.Printf("%q\n", re.FindAllString("paranormal", 2))  // ["ar" "an"]
fmt.Printf("%q\n", re.FindAllString("graal", -1))      // ["aa"]
fmt.Printf("%q\n", re.FindAllString("none", -1))       // [] (nil slice)

There are several more search functions available in the regexp package. The strings All, String, Submatch, and Index can be combined to form the methods:

Find(All)?(String)?(Submatch)?(Index)?

Comments

Be the first to comment!