Regular Expressions in Go: A Powerful Tool for Text Processing
Regular expressions (regex) are an indispensable tool for searching, extracting, and replacing text based on patterns. In the Go language (Golang), working with regular expressions is implemented through the standard regexp package. It provides a fast and safe way to work with patterns, using syntax similar to Perl and RE2. In this article, we will explore the main functions of the package with practical examples.
1. Basics of Working with the regexp Package
The regexp package follows the principle of "compile once, use many times." This improves performance when applying the same pattern repeatedly. Main functions:
regexp.Compile(expr)— compiles a regular expression. Returns*Regexpand an error.regexp.MustCompile(expr)— same as above, but panics on error. Convenient for initializing global variables.regexp.MatchString(expr, s)— checks if stringscontains at least one match to the pattern.
package main
import ( "fmt" "regexp")
func main() { // Simple check: does the string contain digits? matched, _ := regexp.MatchString(`\\d+`, "Order №12345") fmt.Println(matched) // true
// Compile pattern for repeated use re := regexp.MustCompile(`[a-z]+`) fmt.Println(re.MatchString("hello")) // true fmt.Println(re.MatchString("HELLO")) // false}Note: by default, MatchString searches for a partial match (like strings.Contains). For a full string match with the pattern, use anchors ^ and $.
2. Searching and Extracting Data
To find all matches or the first occurrence, use methods FindString, FindAllString, FindStringSubmatch and their byte slice equivalents.
2.1. Finding the First Match
re := regexp.MustCompile(`\\b\\w+@\\w+\\.\\w+\\b`)email := re.FindString("Contact us: support@example.com or info@test.org")fmt.Println(email) // support@example.com2.2. Finding All Matches
re := regexp.MustCompile(`\\d{4}`)numbers := re.FindAllString("Codes: 1234, 5678, 9012", -1)fmt.Println(numbers) // [1234 5678 9012]The second argument of FindAllString is the maximum number of matches. -1 means "all".
2.3. Capture Groups (submatch)
Capture groups allow extracting parts of a match. They are defined with parentheses ().
re := regexp.MustCompile(`(\\w+)@(\\w+\\.\\w+)`)match := re.FindStringSubmatch("user@example.com")fmt.Println(match) // [user@example.com user example.com]// match[0] — full match// match[1] — first group (user)// match[2] — second group (example.com)3. Text Replacement Using Regular Expressions
The regexp package provides two main methods for replacement:
ReplaceAllString(src, repl)— replaces all matches with stringrepl.ReplaceAllStringFunc(src, replFunc)— replaces each match using a callback function.
3.1. Simple Replacement
re := regexp.MustCompile(`\\s+`)result := re.ReplaceAllString("Many spaces here", " ")fmt.Println(result) // "Many spaces here"3.2. Replacement Using Capture Groups
In the replacement string, you can reference groups using $1, $2, etc.
re := regexp.MustCompile(`(\\w+)\\s+(\\w+)`)result := re.ReplaceAllString("John Smith", "$2, $1")