Go's regex support is pretty good.
regexp - The Go Programming Language
Generally you must compile regexes before use with Compile
or MustCompile
. The exception is [MatchString](<https://golang.org/pkg/regexp/#MatchString>)
.
string =~ /regex/
→ regexp.MatchString("regex", string)
— quick boolean test. Also works with compiled regexes.
string =~ /(regex)/
→re.FindString(string)
— first match of entire regex (not capture groups) in string
string =~ /(regex)/g
→re.FindAllString(string)
— all matches of entire regex (not capture groups) in string
string =~ s/regex/replace/g
→ re.ReplaceAllString(string, replace)
Capture groups use the FindStringSubmatch
method.
<aside>
💡 FindString
returns the string that matches the whole regex; FindStringSubmatch
returns the string and capture groups.
</aside>
string =~ /(reg)(exp)/
→ r.FindStringSubmatch
— get slice containing first match in string
string =~ /(reg)(ex)/g
→ r.FindAllStringSubmatch
— get nested slice of captures from all matches
ReplaceAllStringFunc
lets you supply a function which transforms regex matches.
A simplified playground I created which gives examples of the basics