🔎 Go – Regular Expressions Explained with regexp
Package, Syntax & Examples (2025 Guide)
🧲 Introduction – What Are Regular Expressions in Go?
Regular expressions (regex) in Go are handled using the regexp
package, which provides powerful pattern matching for validating, searching, and manipulating strings. Regex in Go is efficient, thread-safe, and widely used for input validation, text extraction, and log processing.
🎯 In this section, you’ll learn:
- How to use the
regexp
package for matching patterns - Write and compile regular expressions in Go
- Use regex methods like
MatchString
,FindString
,ReplaceAllString
- Real-world examples and best practices
✅ Importing the regexp
Package
import "regexp"
✅ All regex-related operations in Go are performed via the standard library’s regexp
package.
🧪 Simple Match Using MatchString
package main
import (
"fmt"
"regexp"
)
func main() {
matched, _ := regexp.MatchString("Go+", "Gooo")
fmt.Println(matched) // Output: true
}
✅ MatchString
returns a boolean indicating whether the input matches the pattern.
🧱 Compile Regex for Reuse
re := regexp.MustCompile(`\d{3}-\d{2}-\d{4}`)
fmt.Println(re.MatchString("123-45-6789")) // Output: true
✅ MustCompile()
panics on invalid regex, suitable for constants. Use Compile()
when error checking is required.
🔍 Extracting Matches – FindString
, FindAllString
text := "My phone numbers are 123-456-7890 and 987-654-3210."
re := regexp.MustCompile(`\d{3}-\d{3}-\d{4}`)
matches := re.FindAllString(text, -1)
fmt.Println(matches) // Output: [123-456-7890 987-654-3210]
✅ FindAllString()
returns all matches; -1
means no limit.
🔁 Replace Content – ReplaceAllString
re := regexp.MustCompile(`[aeiou]`)
result := re.ReplaceAllString("hello world", "*")
fmt.Println(result) // Output: h*ll* w*rld
✅ Use regex to replace characters/patterns in strings.
📤 Capture Groups – FindStringSubmatch
re := regexp.MustCompile(`(\w+)@(\w+\.\w+)`)
match := re.FindStringSubmatch("user@example.com")
fmt.Println(match) // Output: [user@example.com user example.com]
✅ Capture groups allow extraction of subcomponents from a match.
🧰 Validate Input Example – Email
re := regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,}$`)
email := "test@example.com"
if re.MatchString(email) {
fmt.Println("Valid email")
} else {
fmt.Println("Invalid email")
}
📤 Output:
Valid email
✅ Useful for form validation and sanitization.
🧠 Regex Syntax Quick Reference
Pattern | Matches |
---|---|
. | Any single character |
\d | Digit (0–9) |
\w | Word character [a-zA-Z0-9_] |
* | Zero or more |
+ | One or more |
^ | Start of string |
$ | End of string |
[abc] | a, b, or c |
(abc) | Capture group |
📛 Handling Compile Errors
re, err := regexp.Compile("[")
if err != nil {
fmt.Println("Invalid regex:", err)
}
✅ Always validate user-provided patterns to avoid panics.
🧠 Best Practices
Tip | Why It Helps |
---|---|
✅ Use MustCompile for constants | Panics on startup if regex is broken |
✅ Escape special characters | Avoid syntax errors with \. or \\ |
❌ Don’t overuse regex | Use string methods when possible |
✅ Benchmark heavy patterns | Improve performance in large-scale parsing |
📌 Summary – Recap & Next Steps
Go’s regexp
package is a robust tool for pattern matching and manipulation. Whether you’re building validation logic or scraping structured text, regex provides flexible, powerful solutions.
🔍 Key Takeaways:
- Use
regexp.MatchString
,FindString
, andReplaceAllString
for common needs - Compile regex with
MustCompile
orCompile
- Capture groups extract specific submatches
- Prefer readability and performance when using complex patterns
⚙️ Next: Explore Go Text Processing, Log Parsing, or build a Validation Utility with Regex + Struct Tags.
❓ FAQs – Go Regular Expressions
❓ How do I write regex in Go?
✅ Use the regexp
package and raw string literals (backticks) to write patterns.
❓ What does MustCompile()
do?
✅ Compiles a regex pattern and panics if invalid—best for static patterns.
❓ How can I extract parts of a match?
✅ Use FindStringSubmatch()
to get the full match and capture groups.
❓ Can I use regex to validate email or phone numbers?
✅ Yes. Use anchored patterns like ^pattern$
for complete string validation.
❓ Should I always use regex for string matching?
❌ No. Use simpler string functions like strings.Contains
when possible.
Share Now :