In Golang, submatch indexing is used to access captured groups within a regular expression match. The syntax for submatch indexing in Golang is match[i]
, where match
is the result of a regular expression match and i
is the index of the captured group.
Here's an example to illustrate how to use submatch indexing in Golang:
package main
import (
"fmt"
"regexp"
)
func main() {
// Regular expression pattern with two captured groups
re := regexp.MustCompile(`(\w+)\s+(\w+)`)
// Input string to match against
str := "Hello World"
// Find all matches
matches := re.FindAllStringSubmatch(str, -1)
// Access captured groups using submatch indexing
for _, match := range matches {
fmt.Println("Full match:", match[0])
fmt.Println("First captured group:", match[1])
fmt.Println("Second captured group:", match[2])
}
}
In this example, the regular expression pattern (\w+)\s+(\w+)
has two captured groups. The FindAllStringSubmatch
function is used to find all matches in the input string str
. The matches
variable will hold the result, which is a slice of slices, where each slice contains the full match and the captured groups.
The for
loop is used to iterate over each match in the matches
slice. Within the loop, you can access the captured groups using submatch indexing. For example, match[1]
is used to access the first captured group, and match[2]
is used to access the second captured group.
You can modify the regular expression pattern and the input string according to your specific use case, but the concept of submatch indexing remains the same.