Practical Use Cases
Data Validation and Sanitization
Regular expressions are powerful tools for validating and cleaning input data in various scenarios.
Email Validation
package main
import (
"fmt"
"regexp"
)
func validateEmail(email string) bool {
pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
match, _ := regexp.MatchString(pattern, email)
return match
}
func main() {
emails := []string{
"[email protected]",
"invalid-email",
"[email protected]",
}
for _, email := range emails {
fmt.Printf("%s: %v\n", email, validateEmail(email))
}
}
Log File Processing
package main
import (
"fmt"
"regexp"
)
func extractErrorLogs(logContent string) []string {
regex := regexp.MustCompile(`ERROR:\s(.+)`)
matches := regex.FindAllString(logContent, -1)
return matches
}
func main() {
logContent := `
2023-06-15 10:30:45 INFO: Starting service
2023-06-15 10:31:00 ERROR: Database connection failed
2023-06-15 10:31:05 ERROR: Authentication error
2023-06-15 10:32:00 INFO: Service running
`
errorLogs := extractErrorLogs(logContent)
for _, log := range errorLogs {
fmt.Println(log)
}
}
URL Parameter Parsing
package main
import (
"fmt"
"regexp"
)
func parseURLParams(url string) map[string]string {
regex := regexp.MustCompile(`(\w+)=([^&]+)`)
matches := regex.FindAllStringSubmatch(url, -1)
params := make(map[string]string)
for _, match := range matches {
params[match[1]] = match[2]
}
return params
}
func main() {
url := "https://LabEx.com/course?category=golang&level=intermediate"
params := parseURLParams(url)
for key, value := range params {
fmt.Printf("%s: %s\n", key, value)
}
}
Use Case Scenarios
graph TD
A[Regexp Use Cases] --> B[Data Validation]
A --> C[Log Processing]
A --> D[Data Transformation]
A --> E[Security Filtering]
Removing Potentially Dangerous Characters
package main
import (
"fmt"
"regexp"
)
func sanitizeInput(input string) string {
// Remove potentially dangerous characters
regex := regexp.MustCompile(`[<>;&|]`)
return regex.ReplaceAllString(input, "")
}
func main() {
inputs := []string{
"Hello, World!",
"User input with <script>alert('XSS')</script>",
"Dangerous;command",
}
for _, input := range inputs {
sanitized := sanitizeInput(input)
fmt.Printf("Original: %s\nSanitized: %s\n\n", input, sanitized)
}
}
Scenario |
Recommendation |
Simple Matching |
Use regexp.MatchString() |
Repeated Use |
Precompile with regexp.Compile() |
Complex Replacements |
Use ReplaceAllFunc() |
Large Datasets |
Consider alternative parsing methods |
Best Practices
- Always validate and sanitize user inputs
- Precompile regexp patterns for performance
- Use specific, precise patterns
- Handle potential regexp compilation errors
- Consider performance impact of complex patterns