How to Find All Matches with Regex in Go

Use regexp.FindAllString with -1 to retrieve all regex matches in a Go string.

Use regexp.FindAllString to get all matches as a slice of strings, or regexp.FindAllStringSubmatch to capture groups.

package main

import (
	"fmt"
	"regexp"
)

func main() {
	pattern := `\d+`
	text := "Found 123 and 456."
	
	re := regexp.MustCompile(pattern)
	matches := re.FindAllString(text, -1)
	
	fmt.Println(matches) // Output: [123 456]
}

The -1 argument tells the function to find all matches. Use a positive integer to limit the number of results.