How to Use Regular Expressions in Go with regexp

Use the regexp package in Go to compile patterns and match strings with methods like MatchString and FindAllString.

Use the regexp package to compile patterns and match strings. Compile the pattern with regexp.MustCompile or regexp.Compile, then use methods like MatchString to test for a match or FindAllString to extract substrings.

package main

import (
	"fmt"
	"regexp"
)

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

	// Test if the string matches
	if pattern.MatchString("abc123def") {
		fmt.Println("Match found")
	}

	// Find all matches
	matches := pattern.FindAllString("abc123def456", -1)
	fmt.Println(matches) // Output: [123 456]
}