Skip to content

Go Regular Expressions

Regular expressions (regex) are a way to search for patterns in text. Go provides the regexp package for this.

Basic Example

package main

import (
    "fmt"
    "regexp"
)

func main() {
    // 1. Simple match check
    match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
    fmt.Println(match) // true

    // 2. Compile a regex for repeated use (MustCompile panics on error)
    r := regexp.MustCompile("p([a-z]+)ch")

    // Find first match
    fmt.Println(r.MatchString("peach")) // true

    // Find string
    fmt.Println(r.FindString("peach punch")) // peach

    // Find and Replace
    fmt.Println(r.ReplaceAllString("a peach", "<fruit>")) // a <fruit>
}

Common Functions

Function What it does
MatchString Returns true if pattern is found.
FindString Returns the first match found.
FindAllString Returns all matches found in a slice.
ReplaceAllString Replaces all matches with a new string.
Split Splits a string using the regex as a separator.

Submatches (Groups)

Use parentheses () to capture specific parts of a match.

1
2
3
4
r := regexp.MustCompile("p([a-z]+)ch")
res := r.FindStringSubmatch("peach")
fmt.Println(res) // ["peach", "ea"]
// res[0] is the full match, res[1] is the first capture group

Why use Regular Expressions?

  1. Validation: Check if a string is a valid email, phone number, or password.
  2. Extraction: Pull specific data (like dates or IP addresses) out of logs.
  3. Transformation: Clean up or reformat text.

Performance Tip

Always pre-compile your regex using regexp.MustCompile if you're going to use it more than once (e.g., inside a loop). Compiling a regex is expensive!