Go Regular Expressions with the regexp Package

Updated 4 min read
Go Regular Expressions featured image: cards for finding numbers, capture groups and replacing text

Go regular expressions let you search, check and change text using patterns instead of exact words. In this post, you will match text and find every number in a sentence. Then you will pull out parts with capture groups and replace text. Also, each idea comes with a short example that you can run yourself.

Patterns work on text, so first review Go strings explained with examples. We also write patterns inside backticks, the raw strings from that lesson. Finally, we check errors as shown in error handling in Go for beginners.

What Are Go Regular Expressions?

In short, a regular expression, or regex, is a tiny language for describing text. For example, \d+ means “one or more digits”, and ^go means “starts with go”. Think of it as a search with wildcards that understands shapes, such as “an email” or “a date”.

Go regular expressions come from the regexp package. Specifically, it uses the RE2 syntax, which always runs in linear time. In other words, a bad pattern can never freeze your server.

matched, err := regexp.MatchString(`^go`, "golang")
fmt.Println(matched, err) // true <nil>

Compile Once, Use Many Times

re := regexp.MustCompile(`\d+`)

fmt.Println(re.MatchString("order 42"))                     // true
fmt.Println(re.FindString("order 42 and 7"))                // 42
fmt.Println(re.FindAllString("order 42 and 7 and 1000", -1)) // [42 7 1000]
fmt.Println(re.FindStringIndex("order 42"))                 // [6 8]

However, compiling a pattern takes work. So compile it once, often as a package-level variable, and reuse it. MustCompile panics on a bad pattern, which is fine for fixed patterns in your code. For user-supplied patterns, however, use regexp.Compile and check the error.

Validating Input with Go Regular Expressions

email := regexp.MustCompile(`^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$`)

fmt.Println(email.MatchString("asha@example.com")) // true
fmt.Println(email.MatchString("bad@email"))        // false
fmt.Println(email.MatchString("Ravi@Example.com")) // false

Here, the ^ and $ anchors force the whole text to match, not just a part. Notice the last result too. The pattern only allows small letters, so add (?i) at the start to ignore case.

Capture Groups: Pulling Out Parts

In other words, parentheses mark parts of the match that you want to keep. For example, the diagram below shows a date pattern split into three groups.

Go Regular Expressions diagram showing a date pattern with three capture groups and the matched parts

Each pair of parentheses captures one part of the date, and FindStringSubmatch returns the full match followed by every group.

date := regexp.MustCompile(`(\d{4})-(\d{2})-(\d{2})`)
m := date.FindStringSubmatch("Released on 2026-08-20.")
fmt.Println(m)      // [2026-08-20 2026 08 20]
fmt.Println(len(m)) // 4

First of all, index 0 holds the full match, and the groups follow in order. So m[1] is the year, m[2] the month and m[3] the day.

Named Groups

named := regexp.MustCompile(`(?P<year>\d{4})-(?P<month>\d{2})`)
mm := named.FindStringSubmatch("2026-08")
fmt.Println(mm[named.SubexpIndex("year")], mm[named.SubexpIndex("month")]) // 2026 08

Similarly, names make long patterns easier to read. In addition, your code no longer breaks when someone adds a new group in the middle.

Replacing Text with Go Regular Expressions

fmt.Println(date.ReplaceAllString("2026-08-20", "$3/$2/$1")) // 20/08/2026

spaces := regexp.MustCompile(`\s+`)
fmt.Println(spaces.ReplaceAllString("too    many   spaces", " ")) // too many spaces

fmt.Println(regexp.QuoteMeta("1+1=2?")) // 1\+1=2\?

Then, in the replacement, $1, $2 and $3 refer to the groups. QuoteMeta escapes special characters, so user text matches literally.

Go Regular Expressions Cheat Sheet

\d       a digit                         7
\w       a letter, digit or underscore   a
\s       a space, tab or newline
+        one or more                     \d+ matches 2026
*        zero or more                    a* matches aaa
?        optional                        colou?r matches color
{2,}     two or more                     [a-z]{2,} matches com
^ $      start and end                   ^go$ matches go only

When Not to Use Go Regular Expressions

Regex is powerful, but it is not always the best tool. For simple checks, the strings package is faster and easier to read. For example, strings.HasPrefix(s, "go") beats ^go, and strings.Contains beats a plain word pattern.

Also, avoid Go regular expressions for structured formats such as JSON, HTML or full email rules. After all, real parsers handle those edge cases far better. In short, reach for regex when the text has a clear shape but no proper parser exists.

Common Mistakes with Go Regular Expressions

Error you seeWhy it happensHow to fix it
error parsing regexp: invalid or unsupported Perl syntax: (?=Because RE2 has no lookahead.So use capture groups or extra code.
error parsing regexp: missing closing ): (abcBecause a bracket is missing.So balance every parenthesis.
Pattern matches inside a wordBecause anchors are missing.So add ^ and $, or \b.
Backslashes vanishBecause the pattern used double quotes.So use backticks for patterns.

Regex puzzles also appear in coding interviews. So practise with my Go interview questions and answers.

Official Resources

These pages come straight from the Go team, so they stay accurate and up to date.

Quick Recap

  • Go regular expressions live in the regexp package and use RE2 syntax.
  • Compile once with MustCompile and reuse the pattern.
  • Use ^ and $ to match the whole text.
  • Capture groups and FindStringSubmatch pull out parts.
  • RE2 has no lookahead, but it never hangs on bad input.

What’s Next?

Finally, you can search and reshape text with patterns. Next, we will make our programs easier to debug with structured logging using log/slog.

Next lesson: Go Structured Logging with log/slog