Skip to content

Regular expressions

The regexp package provides regular expression search and match. It uses the RE2 syntax (no backtracking, guaranteed linear time).

Match a pattern and extract submatches.

package main
import (
"fmt"
"regexp"
)
func main() {
pattern := regexp.MustCompile(`(\w+)=(\d+)`)
s := "age=30 name=Alice height=175"
matches := pattern.FindAllStringSubmatch(s, -1)
for _, m := range matches {
fmt.Printf("key=%s, value=%s\n", m[1], m[2])
}
// Check if matches
fmt.Println(pattern.MatchString("foo=123"))
}
Terminal window
key=age, value=30
key=name, value=Alice
key=height, value=175
true