Regular expressions
suggest changeGo's standard library has regular expressions in package regexp. The syntax is that of RE2, which is mostly the same as Perl, Python or JavaScript regular expressions, with one important difference: Go guarantees that matching runs in time linear in the size of the input. To make that possible it leaves out backreferences and lookaround.
For simple tasks, functions in strings are faster and easier to read. See Find string in another string, Replace text in strings and Split and join strings. Use a regular expression when you need to match a pattern rather than fixed text.
Compiling a regular expression
A pattern must be compiled into a *regexp.Regexp before you use it. regexp.Compile returns an error if the pattern is invalid:
package main
import (
"fmt"
"regexp"
)
func main() {
// Compile returns an error for an invalid pattern.
re, err := regexp.Compile(`^\d{3}-\d{4}$`)
if err != nil {
fmt.Println("bad pattern:", err)
return
}
fmt.Println(re.MatchString("555-1234"))
fmt.Println(re.MatchString("555-12345"))
_, err = regexp.Compile(`a(b`)
fmt.Println("error:", err)
// One-off check without keeping the compiled regexp.
ok, err := regexp.MatchString(`go+gle`, "gooooogle")
fmt.Println(ok, err)
}
true
false
error: error parsing regexp: missing closing ): `a(b`
true <nil>
Write patterns as raw string literals (backticks). In a regular "..." string you'd have to double every backslash: "\\d+" instead of `\d+`.
When the pattern is a constant in your code, use regexp.MustCompile. It panics on an invalid pattern instead of returning an error. The usual idiom is a package-level variable, so the pattern is compiled once, when the program starts, and a typo shows up immediately:
package main
import (
"fmt"
"regexp"
)
// Compiled once, at program start. Panics if the pattern is invalid,
// which is fine for a pattern that is a constant in the source code.
var reEmail = regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
func main() {
for _, s := range []string{"kjk@example.com", "not an email", "a@b.c"} {
fmt.Printf("%-17q %v\n", s, reEmail.MatchString(s))
}
}
"kjk@example.com" true
"not an email" false
"a@b.c" false
Use regexp.Compile and check the error when the pattern comes from user input or a config file.
A compiled *Regexp is safe for concurrent use by multiple goroutines, so sharing one package-level variable is fine.
Method naming
Regexp has many methods, but their names follow a pattern:
Find(All)?(String)?(Submatch)?(Index)?
Allreturns all non-overlapping matches instead of the first one. These methods take an extra argumentn: the maximum number of matches to return, or-1for all.Stringworks on astring. Without it, the method works on[]byte.Submatchalso returns the text matched by capturing groups (parenthesized parts of the pattern).Indexreturns byte offsets ([start, end]pairs) instead of text.
The same applies to Match/MatchString and ReplaceAll/ReplaceAllString.
Finding matches
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\d+`)
s := "order 66 shipped 3 items for 120 dollars"
fmt.Printf("%q\n", re.FindString(s))
fmt.Println(re.FindStringIndex(s))
fmt.Printf("%q\n", re.FindAllString(s, -1))
fmt.Printf("%q\n", re.FindAllString(s, 2))
fmt.Println(re.FindAllStringIndex(s, -1))
// No match: empty string and nil.
fmt.Printf("%q\n", re.FindString("no digits"))
fmt.Println(re.FindAllString("no digits", -1) == nil)
// FindString can't tell "no match" from "matched an empty string".
// The index form can: nil means no match.
opt := regexp.MustCompile(`a*`)
fmt.Printf("%q %v\n", opt.FindString("bbb"), opt.FindStringIndex("bbb"))
fmt.Println(re.FindStringIndex("bbb") == nil)
}
"66"
[6 8]
["66" "3" "120"]
["66" "3"]
[[6 8] [17 18] [29 32]]
""
true
"" [0 0]
true
Indexes are byte offsets into the string, so s[6:8] is "66".
MatchString only reports whether there's a match anywhere in the string. It doesn't have to match the whole string. Use ^ and $ (or \A and \z) in the pattern to anchor it to the beginning and end.
Capturing groups
Parentheses create a capturing group. FindStringSubmatch returns a slice where index 0 is the whole match and index i is the text of the i-th group:
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(\d{4})-(\d{2})-(\d{2})`)
m := re.FindStringSubmatch("released on 2024-02-06, patched later")
fmt.Printf("%q\n", m)
fmt.Println("year:", m[1], "month:", m[2], "day:", m[3])
fmt.Println("groups:", re.NumSubexp())
// Index pairs: [start, end] for the whole match, then for each group.
fmt.Println(re.FindStringSubmatchIndex("released on 2024-02-06"))
// All matches with their groups.
text := "2024-02-06 and 2025-08-12"
for _, m := range re.FindAllStringSubmatch(text, -1) {
fmt.Println(m[0], "->", m[1], m[2], m[3])
}
}
["2024-02-06" "2024" "02" "06"]
year: 2024 month: 02 day: 06
groups: 3
[12 22 12 16 17 19 20 22]
2024-02-06 -> 2024 02 06
2025-08-12 -> 2025 08 12
If there's no match, FindStringSubmatch returns nil. Always check for it before indexing, or you'll get an index out of range panic.
Named groups
Counting parentheses gets error-prone in longer patterns. A named group is written (?P<name>...), or since Go 1.22 also (?<name>...). SubexpIndex returns the index of a named group, or -1 if there's no group with that name:
package main
import (
"fmt"
"regexp"
)
func main() {
// (?P<name>...) and, since Go 1.22, (?<name>...) both name a group.
re := regexp.MustCompile(`(?P<key>\w+)=(?<value>[^;]*)`)
fmt.Printf("%q\n", re.SubexpNames())
m := re.FindStringSubmatch("theme=dark; lang=en")
fmt.Println("key:", m[re.SubexpIndex("key")])
fmt.Println("value:", m[re.SubexpIndex("value")])
fmt.Println("missing:", re.SubexpIndex("nope"))
// Build a map from all matches.
conf := map[string]string{}
for _, m := range re.FindAllStringSubmatch("theme=dark;lang=en;tz=UTC", -1) {
conf[m[1]] = m[2]
}
fmt.Println(conf)
}
["" "key" "value"]
key: theme
value: dark
missing: -1
map[lang:en theme:dark tz:UTC]
Non-capturing and optional groups
(?:...) groups part of a pattern (for alternation or repetition) without creating a capture. A group that didn't participate in the match returns "", the same as a group that matched an empty string. When the difference matters, use the Index variant: a group that didn't participate has indexes -1, -1:
package main
import (
"fmt"
"regexp"
)
func main() {
// (?:...) groups without capturing.
re := regexp.MustCompile(`(?:Mr|Ms|Dr)\. (\w+)`)
fmt.Printf("%q\n", re.FindStringSubmatch("Hello Dr. Smith"))
// A group that didn't take part in the match is "".
// Use the index form to tell it apart from an empty match.
re2 := regexp.MustCompile(`(\d+)(?:\.(\d*))?`)
for _, s := range []string{"42", "42.", "42.5"} {
m := re2.FindStringSubmatch(s)
idx := re2.FindStringSubmatchIndex(s)
fmt.Printf("%-6q groups=%q frac-index=%v\n", s, m[1:], idx[4:6])
}
}
["Dr. Smith" "Smith"]
"42" groups=["42" ""] frac-index=[-1 -1]
"42." groups=["42" ""] frac-index=[3 3]
"42.5" groups=["42" "5"] frac-index=[3 4]
Replacing
ReplaceAllString replaces every match. In the replacement string, $1 or ${1} refers to a numbered group and $name or ${name} to a named group:
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(\w+)@(\w+)\.com`)
s := "contact: kjk@example.com, bob@test.com"
// $1, $2 refer to groups. ${1} is the unambiguous form.
fmt.Println(re.ReplaceAllString(s, "$2:$1"))
// Pitfall: $1x is parsed as a group named "1x", which doesn't exist.
fmt.Println(re.ReplaceAllString(s, "$1x"))
fmt.Println(re.ReplaceAllString(s, "${1}x"))
// Named groups work the same way.
reDate := regexp.MustCompile(`(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})`)
fmt.Println(reDate.ReplaceAllString("due 2025-08-12", "${d}/${m}/${y}"))
// Literal replacement: $ is not special. Or escape it as $$.
price := regexp.MustCompile(`PRICE`)
fmt.Println(price.ReplaceAllLiteralString("cost: PRICE", "$1.99"))
fmt.Println(price.ReplaceAllString("cost: PRICE", "$$1.99"))
fmt.Println(price.ReplaceAllString("cost: PRICE", "$1.99"))
}
contact: example:kjk, test:bob
contact: ,
contact: kjkx, bobx
due 12/08/2025
cost: $1.99
cost: $1.99
cost: .99
Two traps are visible above:
$nametakes the longest possible sequence of letters, digits and underscores as the name.$1xmeans group1x, which doesn't exist, so it's replaced with an empty string and there's no error. Use${1}x.$is special in the replacement. If the replacement comes from data (user input, a database), useReplaceAllLiteralStringso that$1.99stays$1.99.
Replacing with a function
ReplaceAllStringFunc calls a function for every match and uses its return value as the replacement:
package main
import (
"fmt"
"regexp"
"strconv"
"strings"
)
func main() {
// ReplaceAllStringFunc gets the whole match.
reWord := regexp.MustCompile(`\b\w`)
fmt.Println(reWord.ReplaceAllStringFunc("hello big world", strings.ToUpper))
reNum := regexp.MustCompile(`\d+`)
doubled := reNum.ReplaceAllStringFunc("3 apples and 12 pears", func(s string) string {
n, _ := strconv.Atoi(s)
return strconv.Itoa(n * 2)
})
fmt.Println(doubled)
// The callback doesn't see groups. To use them, loop over
// submatch indexes and build the result yourself.
reTemp := regexp.MustCompile(`(-?\d+(?:\.\d+)?)F\b`)
src := "Today 68F, tonight 50.5F."
var b strings.Builder
last := 0
for _, m := range reTemp.FindAllStringSubmatchIndex(src, -1) {
f, _ := strconv.ParseFloat(src[m[2]:m[3]], 64)
b.WriteString(src[last:m[0]])
fmt.Fprintf(&b, "%.1fC", (f-32)*5/9)
last = m[1]
}
b.WriteString(src[last:])
fmt.Println(b.String())
}
Hello Big World
6 apples and 24 pears
Today 20.0C, tonight 10.3C.
The function receives only the matched text, not the groups. The last part shows the general technique when you need groups: iterate over FindAllStringSubmatchIndex, copy the text between matches and write your own replacement for each match. In the index slice m, m[0]:m[1] is the whole match and m[2*i]:m[2*i+1] is group i.
Expanding a template
ExpandString applies a $1-style template to a single match and appends the result to a []byte. It's useful for extracting and reformatting matches, as opposed to replacing them in place:
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(?m)^([\w-]+):\s*(.*)$`)
headers := "Host: example.com\nAccept: */*\nUser-Agent: curl"
// ExpandString applies a template to one match and appends to dst.
var out []byte
for _, m := range re.FindAllStringSubmatchIndex(headers, -1) {
out = re.ExpandString(out, "$1 => [$2]\n", headers, m)
}
fmt.Print(string(out))
}
Host => [example.com]
Accept => [*/*]
User-Agent => [curl]
Splitting
Split splits a string around matches of the pattern. Like the All methods, it takes a limit n. With n > 0 it returns at most n substrings, and the last one is the unsplit remainder:
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\s*[,;]\s*`)
fmt.Printf("%q\n", re.Split("a , b;c ; d", -1))
fmt.Printf("%q\n", re.Split("a , b;c ; d", 2))
ws := regexp.MustCompile(`\s+`)
fmt.Printf("%q\n", ws.Split(" lots of\tspace ", -1))
}
["a" "b" "c" "d"]
["a" "b;c ; d"]
["" "lots" "of" "space" ""]
A match at the start or end produces an empty string. To split on whitespace, strings.Fields is simpler and drops the empty strings.
Flags, greedy and lazy matching
Flags are set inside the pattern with (?flags). The most useful ones:
i: case-insensitivem: multi-line mode,^and$match at the beginning and end of each line, not only of the whole texts:.also matches\nU: ungreedy, swaps the meaning ofx*andx*?
package main
import (
"fmt"
"regexp"
)
func main() {
// (?i) case-insensitive
fmt.Println(regexp.MustCompile(`(?i)hello`).FindAllString("Hello HELLO hello", -1))
// (?m) multi-line: ^ and $ match at line boundaries
text := "first line\nsecond line\nthird"
fmt.Printf("%q\n", regexp.MustCompile(`^\w+`).FindAllString(text, -1))
fmt.Printf("%q\n", regexp.MustCompile(`(?m)^\w+`).FindAllString(text, -1))
// (?s) lets . match \n
html := "<p>one\ntwo</p>"
fmt.Printf("%q\n", regexp.MustCompile(`<p>.*</p>`).FindString(html))
fmt.Printf("%q\n", regexp.MustCompile(`(?s)<p>.*</p>`).FindString(html))
// Greedy vs. lazy
tags := "<b>bold</b> and <i>italic</i>"
fmt.Printf("%q\n", regexp.MustCompile(`<.+>`).FindString(tags))
fmt.Printf("%q\n", regexp.MustCompile(`<.+?>`).FindAllString(tags, -1))
// Flags can be scoped to a group.
fmt.Println(regexp.MustCompile(`(?i:go)lang`).FindAllString("GOlang golang GOLANG", -1))
}
[Hello HELLO hello]
["first"]
["first" "second" "third"]
""
"<p>one\ntwo</p>"
"<b>bold</b> and <i>italic</i>"
["<b>" "</b>" "<i>" "</i>"]
[GOlang golang]
*, + and ? are greedy: they match as much as possible. Adding ? (*?, +?, ??) makes them lazy, matching as little as possible.
Unicode
Go regular expressions work on UTF-8 text. . and character classes match whole runes (Unicode code points), not bytes. However, the Perl classes \w, \d, \s and \b are ASCII-only. For Unicode-aware matching use \pL (any letter), \p{Lu} (uppercase letter), \pN (any number) or a script like \p{Greek}:
package main
import (
"fmt"
"regexp"
)
func main() {
s := "Ζεύς met Zeus in Kraków"
// \w is ASCII-only: [0-9A-Za-z_]
fmt.Printf("%q\n", regexp.MustCompile(`\w+`).FindAllString(s, -1))
// \pL is any Unicode letter, \p{Greek} a script.
fmt.Printf("%q\n", regexp.MustCompile(`\pL+`).FindAllString(s, -1))
fmt.Printf("%q\n", regexp.MustCompile(`\p{Greek}+`).FindAllString(s, -1))
// . matches one rune (code point), not one byte.
fmt.Printf("%q\n", regexp.MustCompile(`Krak.w`).FindString(s))
// \b is also ASCII-based, so it sees a boundary inside "Kraków".
fmt.Printf("%q\n", regexp.MustCompile(`\b\w+\b`).FindAllString("Kraków", -1))
}
["met" "Zeus" "in" "Krak" "w"]
["Ζεύς" "met" "Zeus" "in" "Kraków"]
["Ζεύς"]
"Kraków"
["Krak" "w"]
If you match words in user-provided text, \w is almost certainly wrong. Use [\pL\pN_] instead.
Escaping user input
To match a literal string that comes from data, escape it with regexp.QuoteMeta. Otherwise characters like ., + or ( are interpreted as regex syntax, which gives wrong matches or a pattern that fails to compile:
package main
import (
"fmt"
"regexp"
)
func main() {
userInput := "1.5+2"
fmt.Println(regexp.QuoteMeta(userInput))
// Without quoting, . and + are metacharacters.
bad := regexp.MustCompile(userInput)
fmt.Println(bad.MatchString("1.5+2"), bad.MatchString("1x55552"))
good := regexp.MustCompile(`\b` + regexp.QuoteMeta(userInput) + `\b`)
fmt.Println(good.MatchString("1.5+2"), good.MatchString("1x55552"))
fmt.Println(good)
}
1\.5\+2
false true
true false
\b1\.5\+2\b
What RE2 doesn't support
To guarantee linear time, Go rejects features that require backtracking. You get an error from Compile:
package main
import (
"fmt"
"regexp"
)
func main() {
for _, p := range []string{`foo(?=bar)`, `(?<!x)y`, `(a)\1`, `a++`} {
_, err := regexp.Compile(p)
fmt.Println(err)
}
}
error parsing regexp: invalid or unsupported Perl syntax: `(?=`
error parsing regexp: invalid named capture: `(?<!x)y`
error parsing regexp: invalid escape sequence: `\1`
error parsing regexp: invalid nested repetition operator: `++`
The unsupported features are lookahead (?=...) / (?!...), lookbehind (?<=...) / (?<!...), backreferences \1, possessive quantifiers a++ and atomic groups (?>...). Usually you can work around them in Go code:
- Instead of lookahead or lookbehind, capture the surrounding text in a group and use only the part you need.
- Instead of a backreference like
(\w+) \1(a repeated word), match(\w+) (\w+)and compare the groups in code. - Instead of a negative lookahead like "lines without ERROR", match all lines and filter with
!re.MatchString(line).
In exchange, regular expressions can't be used for a ReDoS attack. A pattern that takes exponential time in a backtracking engine (PCRE, Java, JavaScript, Python) runs fast in Go:
package main
import (
"fmt"
"regexp"
"strings"
"time"
)
func main() {
// A classic "catastrophic backtracking" pattern. In a backtracking
// engine this takes exponential time on a near-miss input.
re := regexp.MustCompile(`^(a+)+$`)
input := strings.Repeat("a", 50_000) + "!"
start := time.Now()
matched := re.MatchString(input)
elapsed := time.Since(start)
fmt.Println("matched:", matched)
fmt.Println("under 100ms:", elapsed < 100*time.Millisecond)
}
matched: false
under 100ms: true
This makes it safe to run patterns on untrusted input, and even to accept patterns from users. (Go's engine isn't the fastest for every pattern, but it never falls off a cliff.)
Leftmost-first vs. leftmost-longest
When several alternatives can match at the same position, Go (like Perl) picks the first one that matches, in the order written in the pattern. Calling Longest() switches to POSIX semantics, which pick the longest match:
package main
import (
"fmt"
"regexp"
)
func main() {
// Leftmost-first (Perl-like): the first alternative that matches wins.
re := regexp.MustCompile(`go|golang`)
fmt.Println(re.FindString("golang"))
// Leftmost-longest (POSIX): the longest match wins.
re.Longest()
fmt.Println(re.FindString("golang"))
// MustCompilePOSIX gives the same semantics, but only accepts
// POSIX ERE syntax: no \d, no lazy quantifiers.
posix := regexp.MustCompilePOSIX(`[0-9]+|[0-9]+\.[0-9]+`)
fmt.Println(posix.FindString("pi is 3.14"))
_, err := regexp.CompilePOSIX(`\d+`)
fmt.Println(err)
}
go
golang
3.14
error parsing regexp: invalid escape sequence: `\d`
Longest() modifies the Regexp, so call it right after compiling and before sharing the value between goroutines.
Working with []byte and readers
Every method has a []byte variant: drop String from the name. They avoid converting between []byte and string when your data is already bytes, e.g. a file read with os.ReadFile. The Reader variants work on an io.RuneReader, but they only report the position of the first match:
package main
import (
"bytes"
"fmt"
"regexp"
"strings"
)
func main() {
re := regexp.MustCompile(`#[0-9a-fA-F]{6}\b`)
// []byte variants: same names without "String".
css := []byte("a { color: #FF8800; background: #1e1e1e; }")
fmt.Printf("%q\n", re.FindAll(css, -1))
fmt.Println(string(re.ReplaceAllFunc(css, bytes.ToLower)))
// io.RuneReader variants only report the first match's position.
r := strings.NewReader("no color here, then #00ff00")
fmt.Println(re.FindReaderIndex(r))
}
["#FF8800" "#1e1e1e"]
a { color: #ff8800; background: #1e1e1e; }
[20 27]
To process a large file, read it line by line (see Read file line by line) and match each line.
Example: parsing a log file
Putting it together: a parser for web server logs in Common Log Format. The pattern and group indexes are computed once at package level:
package main
import (
"bufio"
"fmt"
"regexp"
"strconv"
"strings"
)
type Request struct {
IP string
Method string
Path string
Status int
Bytes int
}
// Common Log Format, e.g.:
// 127.0.0.1 - - [10/Oct/2025:13:55:36 +0000] "GET /index.html HTTP/1.1" 200 2326
var reLog = regexp.MustCompile(
`^(?<ip>\S+) \S+ \S+ \[[^\]]+\] "(?<method>[A-Z]+) (?<path>\S+) [^"]*" (?<status>\d{3}) (?<bytes>\d+|-)$`)
var (
idxIP = reLog.SubexpIndex("ip")
idxMethod = reLog.SubexpIndex("method")
idxPath = reLog.SubexpIndex("path")
idxStatus = reLog.SubexpIndex("status")
idxBytes = reLog.SubexpIndex("bytes")
)
func parseLine(line string) (Request, bool) {
m := reLog.FindStringSubmatch(line)
if m == nil {
return Request{}, false
}
status, _ := strconv.Atoi(m[idxStatus])
n, _ := strconv.Atoi(m[idxBytes]) // "-" becomes 0
return Request{
IP: m[idxIP],
Method: m[idxMethod],
Path: m[idxPath],
Status: status,
Bytes: n,
}, true
}
const logData = `127.0.0.1 - - [10/Oct/2025:13:55:36 +0000] "GET /index.html HTTP/1.1" 200 2326
10.0.0.7 - alice [10/Oct/2025:13:55:40 +0000] "POST /api/login HTTP/1.1" 401 -
garbage line
10.0.0.7 - alice [10/Oct/2025:13:56:01 +0000] "GET /missing HTTP/2.0" 404 153`
func main() {
sc := bufio.NewScanner(strings.NewReader(logData))
for lineNo := 1; sc.Scan(); lineNo++ {
r, ok := parseLine(sc.Text())
if !ok {
fmt.Printf("line %d: no match\n", lineNo)
continue
}
fmt.Printf("line %d: %+v\n", lineNo, r)
}
}
line 1: {IP:127.0.0.1 Method:GET Path:/index.html Status:200 Bytes:2326}
line 2: {IP:10.0.0.7 Method:POST Path:/api/login Status:401 Bytes:0}
line 3: no match
line 4: {IP:10.0.0.7 Method:GET Path:/missing Status:404 Bytes:153}
Performance
Compiling a regular expression is much more expensive than matching. The most common performance mistake is calling regexp.MustCompile (or regexp.MatchString, which compiles internally) inside a loop or a frequently called function. And when the "pattern" is a fixed string, functions in package strings are faster still:
package main
import (
"regexp"
"strings"
"testing"
)
const line = "2025-10-10 13:55:36 ERROR disk almost full"
var reError = regexp.MustCompile(`ERROR`)
func BenchmarkCompileInLoop(b *testing.B) {
for b.Loop() {
re := regexp.MustCompile(`ERROR`)
re.MatchString(line)
}
}
func BenchmarkPrecompiled(b *testing.B) {
for b.Loop() {
reError.MatchString(line)
}
}
func BenchmarkStringsContains(b *testing.B) {
for b.Loop() {
strings.Contains(line, "ERROR")
}
}
$ go test -bench . -benchmem
BenchmarkCompileInLoop-24 937807 1517 ns/op 1401 B/op 17 allocs/op
BenchmarkPrecompiled-24 23117956 67.45 ns/op 0 B/op 0 allocs/op
BenchmarkStringsContains-24 135454903 9.115 ns/op 0 B/op 0 allocs/op
Recompiling made the check over 20 times slower and caused allocations. strings.Contains was another 7 times faster than the precompiled regexp. See Benchmarks for more on writing benchmarks.
Some other tips:
- Use
MatchStringwhen you only need a yes/no answer. It can stop at the first match and doesn't need to track group positions. - Prefer
FindoverFindSubmatchwhen you don't need the groups. Tracking group positions is extra work for the engine. - Use the
[]bytemethods when your data is already a[]byte. - Anchor patterns with
^when the match must be at the start, so the engine doesn't try every position.