Advanced Matching
Regular Expression Matching
Go provides powerful regular expression capabilities through the regexp
package for advanced string matching.
Basic Regexp Usage
import (
"fmt"
"regexp"
)
func main() {
pattern := `^\d+$` // Matches strings with only digits
match, _ := regexp.MatchString(pattern, "12345")
fmt.Println(match) // true
}
Regexp Compilation and Methods
graph TD
A[Regexp Compilation] --> B[Match Methods]
B --> C[Find Methods]
C --> D[Replace Methods]
func main() {
// Precompile for better performance
regex := regexp.MustCompile(`\w+`)
text := "Hello, LabEx World!"
matches := regex.FindAllString(text, -1)
fmt.Println(matches) // [Hello LabEx World]
}
Advanced Matching Techniques
Technique |
Method |
Description |
Full Match |
MatchString() |
Checks if entire string matches |
Partial Match |
FindString() |
Finds first match in string |
All Matches |
FindAllString() |
Finds all matches |
Replacement |
ReplaceAllString() |
Replaces matched patterns |
Complex Pattern Matching
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() {
fmt.Println(validateEmail("[email protected]")) // true
fmt.Println(validateEmail("invalid-email")) // false
}
func extractNumbers(text string) []string {
regex := regexp.MustCompile(`\d+`)
return regex.FindAllString(text, -1)
}
func main() {
text := "I have 42 apples and 7 oranges"
numbers := extractNumbers(text)
fmt.Println(numbers) // [42 7]
}
- Compile regexps once and reuse
- Use
regexp.MustCompile()
for known good patterns
- Avoid complex patterns in performance-critical code
Error Handling
func safeRegexpMatch(pattern, text string) bool {
regex, err := regexp.Compile(pattern)
if err != nil {
fmt.Println("Invalid regex:", err)
return false
}
return regex.MatchString(text)
}
Advanced Use Cases
- Input validation
- Data extraction
- Text parsing
- Log analysis
Best Practices
- Use raw string literals for regex patterns
- Prefer compiled regexps over
MatchString()
- Test regex patterns thoroughly
- Consider performance impact of complex matching
By mastering these advanced matching techniques, you'll be able to handle complex string processing tasks efficiently in Go.