Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Go Dictionary
  3. regexp Package

regexp Package

Go's regexp package provides pattern matching, string searching, and replacement using regular expressions. You first create a compiled regular expression object with regexp.Compile() or regexp.MustCompile(), then use it to perform operations.

Syntax

import "regexp"

// Compiles a regular expression (returns an error on failure).
re, err := regexp.Compile(`\d+`)

// Panics on failure (suitable for package-level initialization).
re := regexp.MustCompile(`\d+`)

// Checks whether the pattern exists in the string.
ok := re.MatchString("hello123")  // true

// Returns the first matching string.
s := re.FindString("abc123def456")  // "123"

// Returns all matches (n = max count; -1 returns all).
all := re.FindAllString("123 and 456", -1)  // ["123", "456"]

// Replaces all matches with the given replacement string.
result := re.ReplaceAllString("abc123def456", "NUM")

Method List

MethodDescription
regexp.Compile(expr)Compiles the regular expression and returns a Regexp and an error.
regexp.MustCompile(expr)Panics if compilation fails (suitable for initialization).
regexp.MatchString(pattern, s)Checks for a match directly without pre-compiling.
re.MatchString(s)Reports whether the string matches the pattern.
re.FindString(s)Returns the first matching string, or "" if there is no match.
re.FindAllString(s, n)Returns up to n matches as a slice (-1 returns all matches).
re.FindStringSubmatch(s)Returns the full match and all captured subgroups.
re.FindStringIndex(s)Returns the byte positions [start, end] of the first match.
re.ReplaceAllString(s, repl)Replaces all matches with repl.
re.ReplaceAllStringFunc(s, fn)Replaces all matches with the return value of fn.
re.Split(s, n)Splits the string at each match and returns a slice.

Sample Code

package main

import (
    "fmt"
    "regexp"
)

func main() {
    // Basic match check.
    re := regexp.MustCompile(`\d+`)
    fmt.Println("'abc123' contains digits:", re.MatchString("abc123"))
    fmt.Println("'abcdef' contains digits:", re.MatchString("abcdef"))

    fmt.Println()

    // Find the first match.
    text := "Price is 1200, discount is 300."
    fmt.Println("First number:", re.FindString(text))

    // Find all matches.
    all := re.FindAllString(text, -1)
    fmt.Println("All numbers:", all)

    fmt.Println()

    // Use capture groups.
    dateRe := regexp.MustCompile(`(\d{4})-(\d{2})-(\d{2})`)
    dateStr := "Today is 2026-03-05."
    match := dateRe.FindStringSubmatch(dateStr)
    if match != nil {
        fmt.Println("Full match:", match[0])
        fmt.Println("Year:", match[1])
        fmt.Println("Month:", match[2])
        fmt.Println("Day:", match[3])
    }

    fmt.Println()

    // Replacement example.
    emailRe := regexp.MustCompile(`[\w.+-]+@[\w-]+\.[a-z]{2,}`)
    s := "Contact: user@example.com or admin@wp-p.info"
    masked := emailRe.ReplaceAllString(s, "[email hidden]")
    fmt.Println("Masked:", masked)

    // Dynamic replacement using a function.
    numRe := regexp.MustCompile(`\d+`)
    doubled := numRe.ReplaceAllStringFunc("Values are 10 and 20", func(m string) string {
        // Receives the matched number as a string, transforms it, and returns the result.
        return "(" + m + " doubled)"
    })
    fmt.Println("After replacement:", doubled)

    fmt.Println()

    // Split example.
    spaceRe := regexp.MustCompile(`\s+`)
    words := spaceRe.Split("Hello   World  Go", -1)
    fmt.Println("Split result:", words)
}

Notes

Go's regular expressions use RE2 syntax. This differs from Perl-Compatible Regular Expressions (PCRE) in that lookbehind assertions and backreferences are not supported. This is by design — RE2 guarantees linear-time execution.

Using raw string literals (backtick strings) for regular expression patterns removes the need to escape backslashes. For example, you can write `\d+` directly.

regexp.MustCompile() panics if compilation fails. Use it for package-level variable initialization with known-good patterns, and use regexp.Compile() for dynamic patterns such as user input.

If you find any errors or copyright issues, please .