Go Language Regular Expressions

Regular Expression (regex or regexp for short) is a powerful tool for matching strings.

Regular expressions define a pattern that can quickly search, replace, or extract strings matching that pattern. For details, seeRegular Expression Tutorial。

In Go, regular expressions are handled through theregexpImplement with the package.


In the Go languageregexpPackage

The Go standard library providesregexppackage, used to process regular expressions. The followingregexpCommonly used functions and methods in the package:

  1. CompileandMustCompile
    Used to compile regular expressions.Compilereturns a*Regexpan object and an error, whileMustCompilewill directly panic if compilation fails.

  2. MatchString
    Check whether a string matches a regular expression.

  3. FindStringandFindAllString
    Used to find matching strings.FindStringReturns the first match,FindAllStringReturns all matches.

  4. ReplaceAllString
    Used to replace matched strings.

  5. Split
    Splits strings based on the regular expression.


Basic syntax of regular expressions

The following are some commonly used regular expression syntax:

  • .: matches any single character (except newline).
  • *: matches the preceding character 0 or more times.
  • +: matches the preceding character 1 or more times.
  • ?: matches the preceding character 0 or 1 times.
  • \d: matches digit characters (equivalent to[0-9])。
  • \w: matches letters, digits, or underscores (equivalent to[a-zA-Z0-9_])。
  • \s: matches whitespace characters (including spaces, tabs, newlines, etc.).
  • []: matches any one character inside the brackets (e.g.[abc]matcha、borc)。
  • ^: matches the beginning of the string.
  • $: matches the end of the string.

Example code

The following are some examples of using regular expressions in Go:

Example 1: Check whether a string matches a regular expression

Example

package main

import (
    "fmt"
    "regexp"
)

func main() {
    pattern := `^[a-zA-Z0-9]+$`
    regex := regexp.MustCompile(pattern)

    str := "Hello123"
    if regex.MatchString(str) {
        fmt.Println("String matches the regular expression")
    } else {
        fmt.Println("String does not match the regular expression")
    }
}

Example 2: Finding matching strings

Example

package main

import (
    "fmt"
    "regexp"
)

func main() {
    pattern := `\d+`
    regex := regexp.MustCompile(pattern)

    str := "I have 3 apples and 5 bananas"
    matches := regex.FindAllString(str, -1)
    fmt.Println("Numbers found:", matches)
}

Example 3: Replacing matched strings

Example

package main

import (
    "fmt"
    "regexp"
)

func main() {
    pattern := `\s+`
    regex := regexp.MustCompile(pattern)

    str := "Hello    World"
    result := regex.ReplaceAllString(str, " ")
    fmt.Println("Replaced string:", result)
}

Example 4: Splitting strings

Example

package main

import (
    "fmt"
    "regexp"
)

func main() {
    pattern := `,`
    regex := regexp.MustCompile(pattern)

    str := "apple,banana,orange"
    parts := regex.Split(str, -1)
    fmt.Println("String after splitting:", parts)
}

Notes

  1. Performance issues
    Regular expression matching and replacement operations can consume considerable resources, especially when processing large amounts of data. It is recommended to use them cautiously in performance-sensitive scenarios.

  2. Escape characters
    In Go, backslashes in regular expressions\must be written as\\, because the backslash is also an escape character in strings.

  3. Error Handling
    UsageCompilefunction, be sure to check the returned error to avoid program crashes.

other extensions