Practical Applications
Real-World String Pattern Matching Scenarios
String pattern matching is essential in various domains, from data validation to complex text processing. This section explores practical applications that demonstrate the power of pattern matching in Golang.
1. Data Validation
Email Validation
package main
import (
"fmt"
"regexp"
)
func validateEmail(email string) bool {
emailRegex := regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`)
return emailRegex.MatchString(email)
}
func main() {
emails := []string{
"[email protected]",
"invalid-email",
"[email protected]",
}
for _, email := range emails {
fmt.Printf("%s: %v\n", email, validateEmail(email))
}
}
2. Log File Analysis
package main
import (
"fmt"
"regexp"
)
func extractIPAddresses(logContent string) []string {
ipRegex := regexp.MustCompile(`\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b`)
return ipRegex.FindAllString(logContent, -1)
}
func main() {
logContent := `
2023-06-15 10:30:45 INFO 192.168.1.100 User login
2023-06-15 11:45:22 ERROR 10.0.0.55 Connection failed
`
ips := extractIPAddresses(logContent)
fmt.Println("Detected IP Addresses:", ips)
}
Pattern Matching Application Types
Application |
Technique |
Use Case |
Input Validation |
Regex |
Form data checking |
Log Analysis |
Pattern Matching |
Security monitoring |
Data Extraction |
Regex Groups |
Structured text parsing |
Configuration Parsing |
String Methods |
Reading config files |
3. Web Scraping and Text Processing
package main
import (
"fmt"
"regexp"
)
func extractURLs(text string) []string {
urlRegex := regexp.MustCompile(`https?://[^\s]+`)
return urlRegex.FindAllString(text, -1)
}
func main() {
content := `
Check out our website at https://www.LabEx.com
and our blog at http://blog.LabEx.com
`
urls := extractURLs(content)
fmt.Println("Extracted URLs:", urls)
}
Pattern Matching Workflow
graph TD
A[Input Text] --> B{Pattern Matching}
B --> |Validate| C[Data Validation]
B --> |Extract| D[Information Extraction]
B --> |Filter| E[Text Processing]
4. Security and Compliance
Password Strength Checker
func checkPasswordStrength(password string) bool {
lengthRegex := regexp.MustCompile(`.{8,}`)
uppercaseRegex := regexp.MustCompile(`[A-Z]`)
numberRegex := regexp.MustCompile(`[0-9]`)
specialCharRegex := regexp.MustCompile(`[!@#$%^&*()]`)
return lengthRegex.MatchString(password) &&
uppercaseRegex.MatchString(password) &&
numberRegex.MatchString(password) &&
specialCharRegex.MatchString(password)
}
Key Takeaways
- Pattern matching is versatile and powerful
- Choose the right technique for specific requirements
- Consider performance and complexity
- Implement robust error handling
By mastering these practical applications, developers can leverage string pattern matching to solve complex problems efficiently in Golang.