Go by Example

Regular Expressions

Compile a regular expression once, find all matching numbers, and replace the matches.

A regular expression describes a text pattern. Go's regexp package uses RE2 syntax and provides matching, searching, and replacement functions.

Compile a pattern once, find every number in a string, and replace those matches.

package main
 
import (
    "fmt"
    "regexp"
)
 
func main() {
    numbers := regexp.MustCompile("\\d+")
    text := "3 cats, 12 dogs"
    fmt.Println(numbers.FindAllString(text, -1))
    fmt.Println(numbers.ReplaceAllString(text, "N"))
}

In production

Compile repeated patterns once rather than once per request. Go's regexp engine has linear-time matching, but regexp syntax does not support lookarounds or backreferences. Use direct string functions for simple prefix or suffix checks.

Enjoyed this? Get more software craft delivered to your inbox.