Go core
Browse topics

Regular expressions with regexp

Version
1.27
Review
Draft

Summary#

Compile a pattern once, then reuse it to match, extract or replace text. Go uses RE2 syntax and matches in time linear in the input size. Write patterns as raw strings in backquotes.

Syntax#

go
var pattern = regexp.MustCompile(`(?P<name>\w+)`)
matched := pattern.MatchString(text)
groups := pattern.FindStringSubmatch(text)
index := pattern.SubexpIndex("name")
matches := pattern.FindAllString(text, -1)
changed := pattern.ReplaceAllString(text, "${name}_old")

Example#

go
package main

import (
	"fmt"
	"regexp"
)

var (
	logLine = regexp.MustCompile(`^(?P<level>[A-Z]+) user=(?P<user>\w+)$`)
	number  = regexp.MustCompile(`\d+`)
	pair    = regexp.MustCompile(`(\w+)=(\w+)`)
)

func main() {
	line := "WARN user=linh"
	fmt.Println(logLine.MatchString(line), logLine.MatchString("old "+line))

	groups := logLine.FindStringSubmatch(line)
	fmt.Println(groups[logLine.SubexpIndex("level")])
	fmt.Println(groups[logLine.SubexpIndex("user")])
	fmt.Println(logLine.FindStringSubmatch("garbled") == nil)

	fmt.Printf("%q\n", number.FindAllString("disk 2 at 91 percent", -1))

	fmt.Println(pair.ReplaceAllString("cpu=high mem=low", "$2:$1"))
	fmt.Printf("%q\n", pair.ReplaceAllString("a=1", "$1_old"))
	fmt.Printf("%q\n", pair.ReplaceAllString("a=1", "${1}_old"))
}

Expected output#

Text
true false
WARN
linh
true
["2" "91"]
high:cpu low:mem
""
"a_old"

Common mistakes#

A match can occur anywhere in the input unless the pattern is anchored with ^ and $. In a replacement, $1_old names a group called 1_old, which expands to nothing. Write ${1}_old. Index only when the match is non-nil and SubexpIndex is nonnegative. Use regexp.Compile for user-supplied patterns and check the error, since MustCompile panics on invalid input.

Version applicability#

The other forms date back to Go 1.0. The complete example requires Go 1.15 for SubexpIndex. On earlier versions, search SubexpNames for the index.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0