Go📦Standard Libraryintermediate
regexp — Regular Expressions
Go · Standard Library · Run with go run
Explanation
The `regexp` package implements RE2-syntax regular expressions — a syntax with no catastrophic backtracking, so match time is linear in the input. `regexp.MustCompile` compiles a pattern once at startup (panicking on a bad pattern); the compiled `*Regexp` is safe for concurrent use. Methods cover matching, finding, extracting submatches, and replacing.
Real-World Scenario
A log parser extracts the timestamp, level, and message from each line. A single compiled regex with named capture groups pulls all three fields out per line, far more robust than manual string splitting.
Quick Snippet
snippet.go
import "regexp"
// Compile once, reuse everywhere (safe for concurrent use)
var emailRe = regexp.MustCompile(`[\w.]+@[\w.]+\.\w+`)
emailRe.MatchString("contact me@site.com") // true
emailRe.FindString("ping a@b.io now") // "a@b.io"
emailRe.FindAllString(text, -1) // all matches
// Submatches with capture groups
re := regexp.MustCompile(`(\d{4})-(\d{2})-(\d{2})`)
m := re.FindStringSubmatch("2024-01-15")
// m = ["2024-01-15" "2024" "01" "15"]
re.ReplaceAllString("a1b2c3", "") // "abc"Full Example
regexp_pkg.go
// Compile: go run regexp_pkg.go
// Output:
// match: true
// found: a@b.io
// submatch date parts: [2024-01-15 2024 01 15]
// digits removed: abc
package main
import (
"fmt"
"regexp"
)
// Compile once — safe for concurrent reuse
var emailRe = regexp.MustCompile(`[\w.]+@[\w.]+\.\w+`)
func main() {
fmt.Println("match:", emailRe.MatchString("contact me@site.com"))
fmt.Println("found:", emailRe.FindString("ping a@b.io now"))
dateRe := regexp.MustCompile(`(\d{4})-(\d{2})-(\d{2})`)
m := dateRe.FindStringSubmatch("2024-01-15")
fmt.Println("submatch date parts:", m)
digitRe := regexp.MustCompile(`\d`)
fmt.Println("digits removed:", digitRe.ReplaceAllString("a1b2c3", ""))
}
Run command
go run regexp_pkg.go