Finding Multiple Matches
Understanding Multiple Match Methods
In Golang, the regexp
package provides several methods to find multiple matches in a string:
graph TD
A[Multiple Match Methods] --> B[FindAllString]
A --> C[FindAllStringSubmatch]
A --> D[FindAllStringIndex]
FindAllString Method
The FindAllString()
method returns all non-overlapping matches:
package main
import (
"fmt"
"regexp"
)
func main() {
text := "Phone: 123-456-7890, Backup: 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]
}
FindAllStringSubmatch Method
This method returns matches with their submatches:
func main() {
text := "User1: [email protected], User2: [email protected]"
re := regexp.MustCompile(`(\w+)@(\w+)\.(\w+)`)
matches := re.FindAllStringSubmatch(text, -1)
for _, match := range matches {
fmt.Printf("Full: %s, User: %s, Domain: %s, TLD: %s\n",
match[0], match[1], match[2], match[3])
}
}
Match Limit Parameter
The second parameter in FindAllString()
controls the number of matches:
Limit Value |
Behavior |
-1 |
Return all matches |
n |
Return first n matches |
0 |
Return empty slice |
Practical Example
func extractEmails(text string) []string {
re := regexp.MustCompile(`[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}`)
return re.FindAllString(text, -1)
}
func main() {
text := `Contact us at [email protected] or
[email protected] for more information.`
emails := extractEmails(text)
fmt.Println(emails)
// Output: [[email protected] [email protected]]
}
- Compile regexp patterns once
- Use specific patterns to improve matching speed
- Be cautious with complex regular expressions
Error Handling
Always validate and handle potential regexp errors:
func safeExtractMatches(pattern, text string) []string {
re, err := regexp.Compile(pattern)
if err != nil {
fmt.Println("Invalid regexp:", err)
return nil
}
return re.FindAllString(text, -1)
}
Advanced Matching Techniques
graph TD
A[Advanced Matching] --> B[Lookahead]
A --> C[Lookbehind]
A --> D[Non-capturing Groups]
By mastering these multiple match techniques, you can efficiently extract and process complex text patterns in your Golang applications.