๐ŸŽ“ A1Learner
๐Ÿ”
0 of 34 lessons completed

Go Regex

A regex is a pattern that describes matching text. The regexp package searches text with a regex and can replace the parts that match.

FindString pulls out the number

The pattern [0-9]+ means one or more digits. MustCompile builds the pattern and FindString returns the first match.

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile("[0-9]+")
	fmt.Println(re.FindString("Room 42 is ready"))
}

MatchString checks a date shape

The pattern asks for four digits, a dash, two digits, a dash, and two digits. The signs ^ and $ force the match to cover the whole string.

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile("^[0-9]{4}-[0-9]{2}-[0-9]{2}$")
	fmt.Println(re.MatchString("2026-10-25"))
	fmt.Println(re.MatchString("25-10-2026"))
}

ReplaceAllString masks the digits

Every digit becomes a # sign. Letters and spaces stay as they are.

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile("[0-9]")
	fmt.Println(re.ReplaceAllString("Call 555 0199", "#"))
}

Groups split a name

Round brackets mark a group in the pattern. FindStringSubmatch returns the whole match first, then one entry per group.

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile("([A-Za-z]+) ([A-Za-z]+)")
	parts := re.FindStringSubmatch("Hana Lee")
	fmt.Println(parts[0])
	fmt.Println(parts[1])
	fmt.Println(parts[2])
}

Example

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile("[0-9]+")
	line := "Server error, code 42, retry 3"
	fmt.Println(re.FindString(line))
	fmt.Println(re.ReplaceAllString(line, "#"))
}

Key points

  • MustCompile turns a pattern string into a usable pattern.
  • FindString returns the first part of the text that matches.
  • MatchString reports whether the text matches the pattern.
  • ReplaceAllString swaps every match for a replacement.
  • FindStringSubmatch returns the whole match plus each group.

In this example, the pattern [0-9]+ matches one or more digits. The log line holds two numbers, 42 and 3. FindString prints the first number, 42. ReplaceAllString swaps each full number for one # sign and prints the masked line.

Note

Round brackets in a pattern mark a group.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

Which call returns the first part of a string that matches a pattern?