Skip to main content
Go offers built-in support for regular expressions. Here are examples of common regexp-related tasks.

Simple Pattern Matching

Test whether a pattern matches a string:
match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
fmt.Println(match)
// Output: true

Compiled Patterns

For other regexp tasks, compile an optimized Regexp struct:
r, _ := regexp.Compile("p([a-z]+)ch")

// Match test
fmt.Println(r.MatchString("peach"))
// Output: true
Compile patterns once and reuse them for better performance.

Finding Matches

// Find the match text
fmt.Println(r.FindString("peach punch"))
// Output: peach

Finding All Matches

The All variants find all matches in the input:
fmt.Println(r.FindAllString("peach punch pinch", -1))
// Output: [peach punch pinch]

// Limit number of matches
fmt.Println(r.FindAllString("peach punch pinch", 2))
// Output: [peach punch]

fmt.Println(r.FindAllStringSubmatchIndex("peach punch pinch", -1))
// Output: [[0 5 1 4] [6 11 7 10] [12 17 13 16]]

Byte Arguments

Provide []byte arguments and drop String from the function name:
fmt.Println(r.Match([]byte("peach")))
// Output: true

MustCompile for Globals

Use MustCompile for global variables. It panics instead of returning an error:
r = regexp.MustCompile("p([a-z]+)ch")
fmt.Println("regexp:", r)
// Output: regexp: p([a-z]+)ch

String Replacement

Replace matched substrings:
fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))
// Output: a <fruit>

Transform with Functions

Use Func variants to transform matched text:
in := []byte("a peach")
out := r.ReplaceAllFunc(in, bytes.ToUpper)
fmt.Println(string(out))
// Output: a PEACH

Common Methods

Returns true if the pattern matches the string
Returns the leftmost match of the pattern
Returns all matches of the pattern
Replaces matches with a replacement string
Transforms matches using a function

Package Reference

Build docs developers (and LLMs) love