Go语言中的正则表达式库 regexp
提供了强大的文本处理功能,可以帮助我们在文本中查找、匹配和操作字符串。以下是一些常见的应用场景:
package main
import (
"fmt"
"regexp"
)
func main() {
emailRegex := regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
if emailRegex.MatchString("example@example.com") {
fmt.Println("Valid email")
} else {
fmt.Println("Invalid email")
}
}
package main
import (
"fmt"
"regexp"
)
func main() {
text := "The quick brown fox jumps over the lazy dog."
re := regexp.MustCompile("fox")
newText := re.ReplaceAllString(text, "cat")
fmt.Println(newText)
}
package main
import (
"fmt"
"regexp"
)
func main() {
text := "apple,banana,orange"
re := regexp.MustCompile(",")
result := re.Split(text, -1)
fmt.Println(result)
}
package main
import (
"fmt"
"regexp"
)
func main() {
text := "Call me at 123-456-7890 or 987-654-3210"
re := regexp.MustCompile(`\d{3}-\d{3}-\d{4}`)
matches := re.FindAllString(text, -1)
for _, match := range matches {
fmt.Println(match)
}
}
package main
import (
"fmt"
"regexp"
)
func main() {
text := "This is a sample text with several words."
re := regexp.MustCompile(`\w+`)
matches := re.FindAllString(text, -1)
for _, match := range matches {
fmt.Println(match)
}
}
总之,Go语言的正则表达式库 regexp
提供了丰富的功能,可以应用于各种文本处理任务。