Go語言中的正則表達(dá)式庫 regexp
提供了強(qiáng)大的文本處理功能,可以幫助我們在文本中查找、匹配和操作字符串。以下是一些常見的應(yīng)用場景:
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語言的正則表達(dá)式庫 regexp
提供了豐富的功能,可以應(yīng)用于各種文本處理任務(wù)。