Practical Regexp Examples
Real-World Regexp Applications
1. Email Validation
func validateEmail(email string) bool {
pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
regex := regexp.MustCompile(pattern)
return regex.MatchString(email)
}
func main() {
emails := []string{
"[email protected]",
"invalid.email",
"[email protected]",
}
for _, email := range emails {
fmt.Printf("%s: %v\n", email, validateEmail(email))
}
}
func formatPhoneNumber(phone string) string {
regex := regexp.MustCompile(`(\d{3})(\d{3})(\d{4})`)
return regex.ReplaceAllString(phone, "($1) $2-$3")
}
func main() {
numbers := []string{
"5551234567",
"4445556789",
}
for _, number := range numbers {
fmt.Println(formatPhoneNumber(number))
}
}
Common Regexp Patterns
Use Case |
Regexp Pattern |
Description |
URL Validation |
^https?://[^\s/$.?#].[^\s]*$ |
Matches HTTP/HTTPS URLs |
Password Strength |
^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,}$ |
Requires mixed case, numbers |
IP Address |
^(\d{1,3}\.){3}\d{1,3}$ |
Matches IPv4 addresses |
Log Parsing Example
func extractLogDetails(logLine string) map[string]string {
pattern := `(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) \[(\w+)\] (.+)`
regex := regexp.MustCompile(pattern)
matches := regex.FindStringSubmatch(logLine)
if len(matches) < 5 {
return nil
}
return map[string]string{
"date": matches[1],
"time": matches[2],
"level": matches[3],
"message": matches[4],
}
}
func main() {
logLine := "2023-06-15 14:30:45 [ERROR] LabEx service encountered an issue"
details := extractLogDetails(logLine)
fmt.Printf("%+v\n", details)
}
Regexp Workflow
graph TD
A[Input Text] --> B[Define Regexp Pattern]
B --> C[Compile Regexp]
C --> D[Match/Replace Operation]
D --> E[Process Results]
E --> F[Output Transformed Text]
Advanced Replacement Scenarios
Data Masking
func maskSensitiveData(input string) string {
creditCardRegex := regexp.MustCompile(`\d{4}-\d{4}-\d{4}-(\d{4})`)
return creditCardRegex.ReplaceAllString(input, "XXXX-XXXX-XXXX-$1")
}
func main() {
sensitiveText := "Credit Card: 1234-5678-9012-3456"
fmt.Println(maskSensitiveData(sensitiveText))
}
- Precompile regexp patterns
- Use byte slices for large texts
- Limit regexp complexity
- Consider alternative parsing methods
- Benchmark your regexp operations
By mastering these practical examples, you'll become proficient in using regular expressions for text processing in Golang.