How to Use Regex in Go: Syntax and Examples
In Go, you use the
regexp package to work with regular expressions. You create a regex with regexp.Compile or regexp.MustCompile, then use methods like MatchString or FindString to search or match text.Syntax
The regexp package provides functions to compile and use regular expressions. Use regexp.Compile(pattern string) to create a regex object, which returns a compiled regex and an error if the pattern is invalid. Alternatively, regexp.MustCompile(pattern string) compiles the regex and panics if the pattern is wrong, useful for constants.
Common methods on the compiled regex include:
MatchString(s string) bool: checks if the pattern matches the string.FindString(s string) string: returns the first match found.FindAllString(s string, n int) []string: returns all matches up to n.
go
package main import ( "fmt" "regexp" ) func main() { pattern := `^a.*z$` r, err := regexp.Compile(pattern) if err != nil { fmt.Println("Invalid regex pattern") return } text := "abcz" matched := r.MatchString(text) fmt.Println("Match found:", matched) }
Output
Match found: true
Example
This example shows how to compile a regex, check if a string matches, and find all words starting with a capital letter.
go
package main import ( "fmt" "regexp" ) func main() { // Compile regex to find words starting with capital letters r := regexp.MustCompile(`\b[A-Z][a-z]*\b`) text := "Go is Awesome and Easy to Learn" // Check if text contains any capitalized word if r.MatchString(text) { fmt.Println("Text contains capitalized words.") } // Find all capitalized words words := r.FindAllString(text, -1) fmt.Println("Capitalized words found:", words) }
Output
Text contains capitalized words.
Capitalized words found: [Go Awesome Easy Learn]
Common Pitfalls
Common mistakes when using regex in Go include:
- Not checking the error returned by
regexp.Compile, which can cause runtime issues if the pattern is invalid. - Using raw strings incorrectly; remember to escape backslashes properly or use raw string literals with backticks.
- Confusing
MatchString(checks if pattern matches anywhere) withFindString(returns the matched substring).
Example of wrong and right usage:
go
package main import ( "fmt" "regexp" ) func main() { // Wrong: ignoring error pattern := "[a-z" r, _ := regexp.Compile(pattern) // invalid pattern but error ignored fmt.Println(r.MatchString("abc")) // panic or unexpected behavior // Right: check error r2, err := regexp.Compile(pattern) if err != nil { fmt.Println("Error compiling regex:", err) return } fmt.Println(r2.MatchString("abc")) }
Output
Error compiling regex: error parsing regexp: missing closing ]: `[a-z`
Quick Reference
Here is a quick summary of useful regexp methods in Go:
| Method | Description |
|---|---|
| Compile(pattern string) | Compiles regex, returns regex and error |
| MustCompile(pattern string) | Compiles regex, panics if invalid |
| MatchString(s string) bool | Returns true if pattern matches string |
| FindString(s string) string | Returns first match found |
| FindAllString(s string, n int) []string | Returns all matches up to n |
| ReplaceAllString(src, repl string) string | Replaces matches with repl string |
Key Takeaways
Use regexp.Compile or regexp.MustCompile to create regex objects safely.
Always check errors when compiling regex patterns to avoid runtime panics.
Use MatchString to check if a pattern matches anywhere in a string.
Use FindString or FindAllString to extract matching parts from text.
Escape special characters properly or use raw string literals for regex patterns.