Extract groups and submatch indexes
Extract groups and submatch indexes
Parentheses capture parts of a match. FindStringSubmatch returns the first match followed by captured strings in opening-parenthesis order. No match returns nil. Named groups add a readable label; SubexpIndex finds its numeric position. Index methods return byte offsets, not rune counts.
package main
import ( "fmt" "regexp")
func main() { r := regexp.MustCompile(`(?P<item>[a-z]+):([0-9]+)`) m := r.FindStringSubmatch("tea:12 rice:3") if m != nil { fmt.Println(m[0], m[r.SubexpIndex("item")], m[2]) }}Position zero is the entire match. Position one is item and position two is quantity. The pattern is fixed and known to contain item; for configurable patterns check that SubexpIndex is not -1 before indexing. Use FindAllStringSubmatch with a finite maximum count when collecting multiple results.
Expected output:
tea:12 tea 12Distinguish absent and empty groups
package main
import ( "fmt" "regexp")
func main() { r := regexp.MustCompile(`(é)(x)?()`) s := "aé" ix := r.FindStringSubmatchIndex(s) fmt.Println(ix) fmt.Println(s[ix[2]:ix[3]])}Each pair is a half-open byte interval [start,end). The first pair refers to the whole match; é occupies two bytes. An unmatched optional group has -1,-1; the empty participating group has equal nonnegative indexes. Check for nil and negative indexes before slicing. A captured empty string alone cannot distinguish those two cases.
Expected output:
[1 3 1 3 -1 -1 3 3]éTry it locally
Extract the two captured parts of SKU-42 using ^([A-Z]+)-([0-9]+)$. Print them on one line; handle nil with a message.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Text processing 02: Extract groups and submatch indexes
Check the lesson objective before moving on.
What does submatch element zero contain?
What index pair represents an unmatched optional capture?