The regexp package implements RE2 syntax, guaranteeing linear-time matching with no catastrophic backtracking, unlike regex engines in many other languages.
Examples
MustCompile panics on an invalid pattern, so it belongs in a package-level var for patterns known at compile time.
re := regexp.MustCompile(`\d+`)
fmt.Println(re.MatchString("room 42"))
fmt.Println(re.MatchString("no numbers here"))true
falseFind returns only the leftmost match. FindAll returns every non-overlapping match up to a limit; -1 means no limit.
re := regexp.MustCompile(`\d+`)
fmt.Println(re.FindString("room 42, bldg 7"))
fmt.Println(re.FindAllString("room 42, bldg 7", -1))42
[42 7]Parenthesized groups capture. FindStringSubmatch returns the full match at index 0, followed by each group in order.
re := regexp.MustCompile(`(\w+)@(\w+)\.com`)
m := re.FindStringSubmatch("go@dev.com")
fmt.Println(m[0])
fmt.Println(m[1])
fmt.Println(m[2])go@dev.com
go
dev?P<name> names a group; SubexpIndex looks up its position, so results survive a pattern edit that reorders groups.
re := regexp.MustCompile(`(?P\d{4})-(?P\d{2})-(?P\d{2})` )
m := re.FindStringSubmatch("2026-05-25")
year := m[re.SubexpIndex("year")]
fmt.Println(year)2026A replacement string can reference groups with $1, $2, rearranging text in one call instead of just deleting or masking it.
re := regexp.MustCompile(`(\d{4})-(\d{2})-(\d{2})`)
out := re.ReplaceAllString("2026-05-25", "$2/$3/$1")
fmt.Println(out)05/25/2026Split cuts a string at each match, like strings.SplitN but with a regex separator instead of a fixed string.
re := regexp.MustCompile(`\s*,\s*`)
fmt.Println(re.Split("go, rust, python", -1))[go rust python]ReplaceAllString can blank out matched text entirely, a common pattern for redacting sensitive substrings before logging.
re := regexp.MustCompile(`\d{3}-\d{3}-\d{4}`)
masked := re.ReplaceAllString("call 555-123-4567 now", "***-***-****")
fmt.Println(masked)call ***-***-**** now| Function | Description |
|---|---|
Compile(expr) (*Regexp, error) | Parses expr and returns a Regexp, or an error if the syntax is invalid. |
CompilePOSIX(expr) (*Regexp, error) | Like Compile, but uses POSIX leftmost-longest matching semantics. |
MustCompile(str) *Regexp | Like Compile, but panics instead of returning an error. Meant for static patterns. |
| |
MustCompilePOSIX(str) *Regexp | Like CompilePOSIX, but panics instead of returning an error. |
Match(pattern, b) (bool, error) | Reports whether byte slice b contains any match of pattern; compiles pattern each call. |
MatchString(pattern, s) (bool, error) MatchString(`\d+`, "room 42") // true, nil | Same as Match, but takes a string; both recompile on every call, so prefer MustCompile in loops. |
QuoteMeta(s) string | Escapes all regex metacharacters in s, for safely embedding literal text in a pattern. |
Find(b) []byte | Returns the leftmost match in b, or nil if none. |
FindString(s) string re.FindString("room 42") // "42" | Returns the leftmost match in s as a string, or "" if none. |
FindAll(b, n) [][]byte | Returns up to n non-overlapping matches; n = -1 returns all. |
FindAllString(s, n) []string | String version of FindAll. |
FindIndex(b) []int | Returns the [start, end) byte indices of the leftmost match. |
FindStringIndex(s) []int | String version of FindIndex. |
FindSubmatch(b) [][]byte | Returns the match plus each capture group, index 0 being the full match. |
FindStringSubmatch(s) []string | String version of FindSubmatch. |
Every parenthesized group in the pattern gets its own slot in the returned slice. Index 0 is always the full match; index 1 is the first group, index 2 the second, and so on. A nil return means no match at all. | |
FindAllSubmatch(b, n) [][][]byte | FindSubmatch repeated over up to n matches. |
FindAllStringSubmatch(s, n) [][]string | String version of FindAllSubmatch. |
FindSubmatchIndex(b) []int | Index pairs for the full match and every capture group. |
FindStringSubmatchIndex(s) []int | String version of FindSubmatchIndex. |
ReplaceAll(src, repl) []byte | Replaces every match in src with repl, which may reference groups via $1, $2. |
ReplaceAllString(src, repl) string re.ReplaceAllString("2026-05-25", "$2/$3/$1") // "05/25/2026" | String version of ReplaceAll. |
A replacement string can reference captured groups with | |
ReplaceAllLiteralString(src, repl) string | Like ReplaceAllString, but repl is inserted literally, ignoring $ group references. |
ReplaceAllFunc(src, repl) []byte | Calls repl(match) for each match and substitutes its return value. |
ReplaceAllStringFunc(src, repl) string | String version of ReplaceAllFunc. |
Split(s, n) []string | Splits s at each match, like strings.SplitN but with a regex separator. |
String() string | Returns the source pattern the Regexp was compiled from. |
NumSubexp() int | Returns the number of capture groups in the pattern. |
SubexpNames() []string | Returns each group's name, or "" for unnamed groups; index 0 is always "". |
SubexpIndex(name) int | Returns the index of a named group, or -1 if the name doesn't exist. |
Longest() | Switches the Regexp to prefer the leftmost-longest match, POSIX-style. |
Match(b) bool | Reports whether the compiled Regexp matches anywhere in b (Regexp method). |
MatchString(s) bool | String version of Match (Regexp method). |
Pattern syntax
| Pattern | Description |
|---|---|
. | Any character except newline. |
* | Zero or more of the preceding element. |
+ | One or more of the preceding element. |
? | Zero or one of the preceding element. |
{n,m} | Between n and m repetitions; {n} means exactly n, {n,} means n or more. |
[abc] | Character class: any one of a, b, or c. |
[^abc] | Negated class: any character except a, b, or c. |
[a-z] | Character range from a to z. |
\d | Digit; equivalent to [0-9]. \D negates it. |
\w | Word character; equivalent to [0-9A-Za-z_]. \W negates it. |
\s | Whitespace character. \S negates it. |
^ | Start of string, or start of line in multi-line mode. |
$ | End of string, or end of line in multi-line mode. |
\b | Word boundary. \B is a non-word boundary. |
(re) | Capturing group; matched text is retrievable by position. |
(?P<name>re) | Named capturing group; matched text is retrievable by name via SubexpIndex. |
(?:re) | Non-capturing group; groups for precedence without adding a capture index. |
a|b | Alternation: matches a or b. |
(?i) | Case-insensitive flag for the rest of the pattern (or a scoped group). |
(?s) | Dot-matches-newline flag: makes . match \n too. |
(?m) | Multi-line flag: makes ^ and $ match at line boundaries, not just string ends. |