Regular Expressions in Go with Examples: In Practice
Regular expressions (regex) are a powerful tool for searching, extracting, and replacing text based on a pattern. In Go (Golang), the standard regexp package is used for this purpose, providing an efficient and safe API. In this article, we will break down the main capabilities of the package with specific examples that will help you immediately apply the knowledge in real projects.
Basics of the regexp Package in Go
The regexp package implements regular expression syntax compatible with RE2 (with the exception of backreferences and lookahead/lookbehind). This makes it fast and predictable. Main functions:
regexp.Compile(pattern)— compiles a pattern into aRegexpobject. Returns an error if the pattern is invalid.regexp.MustCompile(pattern)— does the same but panics on error. Convenient for static patterns.MatchString(pattern, s)— checks if the stringscontains a substring matching the pattern.
Always use Compile for dynamic patterns (e.g., from user input) and MustCompile for hardcoded ones.
package main
import ( "fmt" "regexp")
func main() { // Use MustCompile for a static pattern re := regexp.MustCompile(`hello`) match := re.MatchString("hello world") fmt.Println(match) // true
// Compile for a dynamic pattern pattern := "[0-9]+" re2, err := regexp.Compile(pattern) if err != nil { fmt.Println("Compilation error:", err) return } fmt.Println(re2.MatchString("abc123")) // true}Searching and Extracting Data
Often you need not just to check for a match, but to extract specific parts of a string. The methods FindString, FindStringSubmatch, and FindAllString are used for this.
Extracting the First Match
package main
import ( "fmt" "regexp")
func main() { re := regexp.MustCompile(`\\d+`) text := "Code: 12345, price: 678" // First match first := re.FindString(text) fmt.Println(first) // 12345 // All matches all := re.FindAllString(text, -1) fmt.Println(all) // [12345 678]}Extracting Groups (Submatches)
Groups in a pattern (denoted by parentheses) allow you to extract parts of a match. The FindStringSubmatch method returns a slice where the first element is the full match, and subsequent elements are the group values.
package main
import ( "fmt" "regexp")
func main() { // Pattern: username @domain re := regexp.MustCompile(`(\\w+)@(\\w+\\.\\w+)`) email := "user@example.com" match := re.FindStringSubmatch(email) if len(match) > 0 { fmt.Println("Full email:", match[0]) // user@example.com fmt.Println("Username:", match[1]) // user fmt.Println("Domain:", match[2]) // example.com }}The FindAllStringSubmatch method does the same for all matches in the string.
Text Replacement Using Regular Expressions
The regexp package provides two methods for replacement: ReplaceAllString (simple replacement) and ReplaceAllStringFunc (replacement using a function).
Simple Replacement
package main
import ( "fmt" "regexp")
func main() { re := regexp.MustCompile(`\\s+`) // one or more spaces text := "Hello World Go" result := re.ReplaceAllString(text, " ") fmt.Println(result) // Hello World Go}Replacement Using Groups
In the replacement string, you can refer