SoFunction
Updated on 2025-04-08

Common regular expression operations of regexp package in Go

In Golang,regexpPackage is used to handle regular expression operations. Here are some common regular expression operations code examples:

1. Simple MatchString

Used to check if a string matches a regular expression.

package main

import (
	"fmt"
	"regexp"
)

func main() {
	pattern := `^hello`
	text := "hello world"

	match, _ := (pattern, text)
	("Matched:", match) // Output: Matched: true}

2. Compile regular expressions (Compile and MustCompile)

passorCompile regular expressions to improve performance.

package main

import (
	"fmt"
	"regexp"
)

func main() {
	// Compile returns error, if the regular is invalid	re, err := (`\d+`)
	if err != nil {
		("Error compiling regex:", err)
		return
	}

	text := "Order number 12345"
	("Matched:", (text)) // Output: Matched: true
	// MustCompile will panic, if the regular is invalid	re2 := (`\d+`)
	("Matched:", (text)) // Output: Matched: true}

3. Find the first match in the string (FindString and FindStringSubmatch)

  • FindStringReturns the first matching string.
  • FindStringSubmatchReturns the first matching string and the captured subgroup.
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := (`(\d+)-(\d+)-(\d+)`)
	text := "Today's date is 2025-01-25."

	// Find the first matching string	match := (text)
	("Found:", match) // Output: Found: 2025-01-25
	// Find the first match and its subgroup	submatches := (text)
	("Submatches:", submatches) // Output: Submatches: [2025-01-25 2025 01 25]}

4. Find all matches (FindAllString and FindAllStringSubmatch)

  • FindAllStringReturns all matching strings.
  • FindAllStringSubmatchReturns all matching strings and their subgroups.
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := (`\d+`)
	text := "Numbers: 123, 456, and 789."

	// Find all matching strings	matches := (text, -1)
	("Matches:", matches) // Output: Matches: [123 456 789]
	// Limit the number of matches returned	limitedMatches := (text, 2)
	("Limited Matches:", limitedMatches) // Output: Limited Matches: [123 456]}

5. ReplaceAllString

Used to replace all matching strings.

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := (`\d+`)
	text := "Order 123, 456, and 789."

	// Replace all matching numbers as XXX	result := (text, "XXX")
	("Replaced:", result) // Output: Replaced: Order XXX, XXX, and XXX.}

6. ReplaceAllStringFunc

Dynamically replace the matching string with a function.

package main

import (
	"fmt"
	"regexp"
	"strings"
)

func main() {
	re := (`[a-z]+`)
	text := "hello world GO!"

	// Replace the matching string with uppercase	result := (text, )
	("Replaced:", result) // Output: Replaced: HELLO WORLD GO!}

7. Split string

Splitting strings using regular expressions.

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := (`\s+`) // Match whitespace characters	text := "Split   this     string!"

	// Split string	parts := (text, -1)
	("Parts:", parts) // Output: Parts: [Split this string!]}

8. Extract subgroups and name them (Named Captures)

Extract specific subgroups by naming capture groups.

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := (`(?P<Year>\d{4})-(?P<Month>\d{2})-(?P<Day>\d{2})`)
	text := "Date: 2025-01-25."

	// Extract all subgroups	submatches := (text)
	("Submatches:", submatches) // Output: Submatches: [2025-01-25 2025 01 25]
	// Extract named subgroups	names := ()
	for i, name := range names {
		if name != "" {
			("%s: %s\n", name, submatches[i])
		}
	}
	// Output:	// Year: 2025
	// Month: 01
	// Day: 25
}

9. Check the string start position matching (MatchString and Match)

  • MatchStringCheck the entire string.
  • MatchCheck the byte slice.
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := (`^hello`)

	text := "hello world"
	bytes := []byte("hello bytes")

	("String Match:", (text)) // Output: String Match: true	("Bytes Match:", (bytes))      // Output: Bytes Match: true}

10. ReplaceAll

Similar to string operations, but acts on byte slices.

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := (`\d+`)
	text := []byte("Order 123, 456, and 789.")

	// Replace all matching numbers as XXX	result := (text, []byte("XXX"))
	("Replaced:", string(result)) // Output: Replaced: Order XXX, XXX, and XXX.}

This is the article about common regular expression operations in the regexp package in Go. For more related contents of Go regexp regular expression operations, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!