Include in the imports:
import "regexp"
For full package documentation see here
NB. Many functions available in this package have a version that works on strings (e.g. FindAllStringIndex) and a version that works on a slice of bytes (e.g. FindAllIndex).
In this cheatsheet I show the string versions
matched, err := regexp.MatchString("\w+", "hello world")
// => true, nil
matched, err := regexp.MatchString("\d+", "hello world")
// => false, nil
re, err := regexp.Compile("\d+")
Panics if the regex expression cannot be parsed:
re := regexp.MustCompile("\d+")
re, _ := regexp.Compile("\d+")
matched := re.Match("10 green bottles")
// => true
matched := re.Match("ten green bottles")
// => false
re, _ := regexp.Compile("foo.")
result := re.FindString("april fool football")
// => "fool"
result = re.FindString("april showers")
// => ""
Returns a slice of matches.
Second argument indicates how many matches to return if > 0.
-1 indicates return all matches.
re, _ := regexp.Compile(".aa")
matches := re.FindAllString("faa baa haa", -1)
// => ["faa", "baa", "haa"]
matches = re.FindAllString("faa baa haa", 2)
// => ["faa", "baa"]
Returns a slice of indices indicating where the first match is found
The match is at s[loc[0]:loc[1]]
The second index is non-inclusive. Returns nil
if match not found
re, _ := regexp.Compile(".aa")
indices := re.FindStringIndex("faa baa")
// => [0, 3]
indices := re.FindStringIndex("helpful goat")
// => nil
## Return positions of all matches
re, _ := regexp.Compile(".aa")
indices := re.FindAllStringIndex("faa baa")
// => [ [0, 3], [4, 7] ]
Replace all matching substrings in the first argument with the string provided as the second argument
re, _ := regexp.Compile("\.")
replaced := re.ReplaceAllString("123.346.789", "_")
// => "123_456_789"
Find the first (leftmost) match and the matches of its subexpressions (capture groups)
Returns a slice containing the full match followed by subexpressions:
time := "03:24"
re := regexp.MustCompile(`(\d+):(\d+)`)
matches := re.FindStringSubmatch(time)
// ["03:24", "03", "24"]
Find all matches, including matches of each one's subexpressions (capture groups)
Returns a slice of slices:
time := "03:24 18:45"
re := regexp.MustCompile(`(\d+):(\d+)`)
matches := re.FindAllStringSubmatch(time, -1)
// [["03:24", "03", "24"], ["18:45", "18", "45"]]