[Go] Get capture groups from every regular expression match

Created on November 30, 2026

You can use FindAllStringSubmatch from the regexp package to get each match along with its capture groups. Pass -1 as the second argument to return all matches.

package main

import (
    "fmt"
    "regexp"
)

func main() {
    text := "abc adc aec"
    pattern := regexp.MustCompile(`a(.+?)c`)
    matches := pattern.FindAllStringSubmatch(text, -1)
    fmt.Println(matches)
}

Each inner slice starts with the full match, followed by the capture groups in their order in the expression.

[[abc b] [adc d] [aec e]]
Go