Regular Expressions in Go with Examples: In Practice
\n\nRegular expressions (regexp) are a powerful tool for searching, extracting, and replacing text based on patterns. In Go (Golang), working with regex is implemented through the standard regexp package. In this article, we will cover the main functions, syntax, and provide practical examples to help you confidently use regular expressions in your projects.
Basics of the regexp Package
\n\nThe regexp package provides two main ways to compile a regular expression:
- \n
regexp.Compile(pattern string) (*Regexp, error)— compiles the pattern and returns aRegexpobject or an error if the pattern is invalid. \n regexp.MustCompile(pattern string) *Regexp— does the same but callspanicon error. Convenient for static patterns defined at initialization time. \n
It is recommended to use MustCompile for patterns that are guaranteed to be correct (e.g., hardcoded in the code) and Compile for dynamic patterns obtained from the user or an external source.
Example 1: Finding a Substring (FindString)
\n\nThe FindString function returns the first match of the pattern as a string. If there are no matches, it returns an empty string.
package main\n\nimport (\n "fmt"\n "regexp"\n)\n\nfunc main() {\n text := "My email: example@mail.com, backup: test@example.org"\n pattern := `[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}`\n\n re := regexp.MustCompile(pattern)\n match := re.FindString(text)\n\n fmt.Println("Found email:", match) // Output: example@mail.com\n}\n\nExample 2: Finding All Matches (FindAllString)
\n\nTo find all matches, use FindAllString. The second argument is the maximum number of matches (-1 for all).
package main\n\nimport (\n "fmt"\n "regexp"\n)\n\nfunc main() {\n text := "Codes: ABC-123, XYZ-456, QWE-789"\n pattern := `[A-Z]{3}-\\d{3}`\n\n re := regexp.MustCompile(pattern)\n matches := re.FindAllString(text, -1)\n\n fmt.Println("Found codes:", matches)\n // Output: [ABC-123 XYZ-456 QWE-789]\n}\n\nExample 3: Replacing Text (ReplaceAllString)
\n\nReplaceAllString replaces all matches of the pattern with the specified string. You can use capture groups with the syntax $1, $2, etc.
package main\n\nimport (\n "fmt"\n "regexp"\n)\n\nfunc main() {\n text := "Date: 2024-01-15, another date: 2023-12-31"\n pattern := `(\\d{4})-(\\d{2})-(\\d{2})`\n\n re := regexp.MustCompile(pattern)\n // Change format from YYYY-MM-DD to DD.MM.YYYY\n result := re.ReplaceAllString(text, "$3.$2.$1")\n\n fmt.Println("Result:", result)\n // Output: Date: 15.01.2024, another date: 31.12.2023\n}\n\nExample 4: Checking if a String Matches a Pattern (MatchString)
\n\nThe MatchString function returns true if the string contains at least one match of the pattern.
package main\n\nimport (\n "fmt"\n "regexp"\n)\n\nfunc main() {\n emails := []string{"user@example.com", "invalid-email", "admin@site.org"}\n pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$`\n\n re := regexp.MustCompile(pattern)\n for _, email := range emails {\n if re.MatchString(email) {\n fmt.Printf("'%s' — valid email\\n", email)\n } else {\n fmt.Printf("'%s' — NOT a valid email\\n", email)\n }\n }\n // Output:\n // 'user@example.com' — valid email\n // 'invalid-email' — NOT a valid email\n // 'admin@site.org' — valid email\n}\n\nExample 5: Extracting Data Using Capture Groups (FindStringSubmatch)
\n\nFindString