Go 1.27 reference · Formatting, Strings and Text

Go regexp.MustCompile Function

Compile a regular expression (RE2 syntax, linear time) and use it to match, find and replace text.

Go 1.27

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

func MustCompile(str string) *Regexp

Parameters

ParameterDescription
MatchString Does it match?
FindStringSubmatch First match and its groups.
FindAllString(s, -1) All matches.
ReplaceAllString Replace, with $1 for groups.

Examples

Example 1
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`order=(\d+)`)
	fmt.Println(re.MatchString("ref order=42"))
	fmt.Println(re.FindStringSubmatch("ref order=42")[1])
	fmt.Println(re.FindAllString("order=1 order=22", -1))
}

Output

true
42
[order=1 order=22]

Run this on your computer — see “Get Started” for setup.

Replace with groups
package main

import (
	"fmt"
	"regexp"
)

func main() {
	date := regexp.MustCompile(`(\d{4})-(\d{2})-(\d{2})`)
	fmt.Println(date.ReplaceAllString("due 2026-01-15", "$3.$2.$1"))
}

Output

due 15.01.2026

Run this on your computer — see “Get Started” for setup.

Compile patterns once (package-level var re = regexp.MustCompile(...)), not inside loops. Go's RE2 engine has no backreferences or lookaround but can't be made to run in exponential time.

Was this page helpful?