regexp
regexp compiles a pattern once and runs it many times. The engine is a finite automaton, so matching is linear in the input and cannot be driven into the exponential backtracking that a backtracking engine allows; the price is no backreferences and a smaller syntax. A compiled expression is safe for concurrent use, which is why a package-level var is the usual home for one.
MatchString and FindString
MatchString answers whether the pattern occurs anywhere in the input, and FindString returns the first occurrence. FindAllString with a count of -1 returns every non-overlapping match. The pattern below matches an email-shaped word, and the raw string keeps the backslashes readable.
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\b\w+@\w+\.\w+\b`)
fmt.Println("match:", re.MatchString("write to ada@example.com"))
fmt.Println("find:", re.FindString("write to ada@example.com"))
fmt.Println("all:", re.FindAllString("ada@example.com and grace@example.org", -1))
}
go build -o app main.go && ./app
match: true
find: ada@example.com
all: [ada@example.com grace@example.org]
The match is a substring, not the whole input: a pattern is anchored only with ^ and $, and a program that validates a whole string wraps it, as in ^pattern$. The email pattern above is deliberately loose; a real validator is longer, and a real email address is not a regular language at all.
Named groups
Parentheses capture a sub-match, and (?P<name>...) gives the group a name. The full match is element zero of the result and the groups follow in order, so SubexpIndex turns a name into the index and SubexpNames lists them. A named group is also the key of FindStringSubmatch in SubexpIndex-driven code and of the $name form in a replacement.
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})`)
m := re.FindStringSubmatch("date: 2026-11-18")
fmt.Println("whole:", m[0])
fmt.Println("year:", m[re.SubexpIndex("year")])
fmt.Println("month:", m[re.SubexpIndex("month")])
fmt.Println("day:", m[re.SubexpIndex("day")])
fmt.Printf("names: %q\n", re.SubexpNames())
}
go build -o app main.go && ./app
whole: 2026-11-18
year: 2026
month: 11
day: 18
names: ["" "year" "month" "day"]
The first name is empty because index zero is the whole match. A group that did not take part is an empty string in the slice, and a match that failed is a nil slice, so a program checks m == nil before indexing. The date pattern accepts 2026-99-99, which is why a parser or a date layout is better for dates.
Replace
ReplaceAllString replaces every match with a template in which $1 is the first group and ${name} a named one. ReplaceAllStringFunc takes a function instead, which is how a program transforms the matches it found without writing a loop. The $2:$1 template swaps two groups.
package main
import (
"fmt"
"regexp"
"strings"
)
func main() {
spaces := regexp.MustCompile(`\s+`)
fmt.Printf("collapsed: %q\n", spaces.ReplaceAllString("a b \t c", " "))
words := regexp.MustCompile(`\w+`)
fmt.Println("upper:", words.ReplaceAllStringFunc("one two", strings.ToUpper))
at := regexp.MustCompile(`(\w+)@(\w+)`)
fmt.Println("swapped:", at.ReplaceAllString("ada@example", "$2:$1"))
}
go build -o app main.go && ./app
collapsed: "a b c"
upper: ONE TWO
swapped: example:ada
The first call collapsed a run of spaces and a tab into one space, the second uppercased each word, and the third swapped the two groups. A literal dollar in a replacement is written $$; without it the next character is read as a group name.
A bad pattern
MustCompile panics on a bad pattern, which is right for a constant in a program and wrong for a pattern a user typed. Compile returns the error instead, and the text names the problem and the pattern. The pattern below is one unmatched parenthesis.
package main
import (
"fmt"
"regexp"
)
func main() {
_, err := regexp.Compile(`(`)
fmt.Println("error:", err)
}
go build -o app main.go && ./app
error: error parsing regexp: missing closing ): `(`
The message quotes the whole pattern after the reason, which is enough to find the typo. A program that builds a pattern from user input compiles it with Compile and returns the error with a 400, and a program that interpolates a literal string into a pattern calls regexp.QuoteMeta first.
Regexp or a parser
A regular expression is the right tool for a search in text, a loose validation, a split or a rewrite. It is the wrong tool for a nested structure, for a format with balanced delimiters, and for anything where the error has to name a line and a column: those need a parser, and the capstone project in Part 10 builds one. A pattern that has grown to several lines or that a colleague cannot read in a minute is a signal to write the loop instead.
Three habits keep a pattern maintainable. Compile once at package level and not inside a request. Give the groups names. And test the pattern with the inputs that should not match, because a pattern that accepts too much passes every happy-path test.
Exercises
- Anchor the email pattern with ^ and $ and test it with "ada@example.com!". What changes, and why?
- Replace the date pattern with one that accepts only months 01 to 12. Is the result still readable, and what would a parser do better?
- Use FindStringIndex on a match and print the byte range. Why is the second number the end and not the length?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does MustCompile do with a bad pattern?
Answer
Panics
Compile is the version that returns the error.
-
What does MatchString report?
Answer
Whether the pattern occurs anywhere in the input
Anchors are needed for a whole-string match.
-
What does FindAllString with -1 return?
Answer
Every non-overlapping match
A positive count is a limit.
-
Which element of a submatch slice is the whole match?
Answer
Zero
SubexpNames starts with an empty name for it.
-
How does a replacement write the second group?
Answer
$2
$$ is a literal dollar.
-
When is MustCompile the wrong choice?
Answer
For a pattern that comes from user input
It panics instead of returning the error.
-
What does QuoteMeta do?
Answer
Escapes the metacharacters of a literal string
It makes a literal safe to interpolate.
-
Why can a Go regexp not backtrack exponentially?
Answer
It runs on a finite automaton, so matching is linear
No backreferences are supported either.
-
Which job is a regular expression bad at?
Answer
Parsing balanced brackets
Nested structure needs a parser.
-
Why test a pattern with inputs that should not match?
Answer
A too-permissive pattern passes every happy path
The negative cases are the ones that catch it.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev