Method names follow: Find[All][String][Submatch][Index]. Think of it as four axes. All = return every match. String = work on strings rather than []byte. Submatch = include capture groups. Index = return offsets instead of matched text.
FindString / FindAllString
re := regexp.MustCompile(`\d+`)
fmt.Println(re.FindString("abc 12 def 34")) // "12"
fmt.Println(re.FindAllString("abc 12 def 34", -1)) // ["12" "34"]
fmt.Println(re.FindAllString("a1 b2 c3", 2)) // ["1" "2"] — cap at 2
Output
12
[12 34]
[1 2]
FindStringSubmatch — capture groups
re := regexp.MustCompile(`(\w+)=(\w+)`)
m := re.FindStringSubmatch("name=ada")
// m[0] = whole match, m[1..] = groups
fmt.Println(m[0], m[1], m[2])
Output
name=ada name ada
Named groups + SubexpIndex
re := regexp.MustCompile(`(?P<key>\w+)=(?P<val>\w+)`)
m := re.FindStringSubmatch("name=ada")
fmt.Println(m[re.SubexpIndex("key")], m[re.SubexpIndex("val")])
Output
name ada
FindStringIndex — positions instead of text
re := regexp.MustCompile(`\d+`)
loc := re.FindStringIndex("abc 12 def")
fmt.Println(loc) // [4 6]
fmt.Println("abc 12 def"[loc[0]:loc[1]])
Output
[4 6]
12