Go by Example

Regular Expressions

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

A regular expression is a pattern used to find or replace text. Go's regexp package provides functions to check whether text matches a pattern, find matching text, and replace it.

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 a pattern once when you will use it many times. For a simple check such as whether text starts or ends with a word, use a strings function because it is easier to read.

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