通过正则表达式模式查找文本中的子字符串
Golang 版本
1.12.1
前言
总是有一些任务,例如输入验证,在文档中搜索任何信息,甚至从不需要的转义字符中清除给定的字符串。对于这些情况,通常可以使用正则表达式。
实现
package main
import (
"fmt"
"regexp"
)
const refString = `[{ \"email\": \"email@example.com\" \
"phone\": 555467890},
{ \"email\": \"other@domain.com\" \
"phone\": 555467890}]`
func main() {
// 为简洁起见,简化了这种模式
emailRegexp := regexp.MustCompile("[a-zA-Z0-9]{1,}@[a-zA-Z0-9]{1,}\\.[a-z]{1,}")
first := emailRegexp.FindString(refString)
fmt.Println("First: ")
fmt.Println(first)
all := emailRegexp.FindAllString(refString, -1)
fmt.Println("All: ")
for _, val := range all {
fmt.Println(val)
}
}
$ go run regexp.go First: email@example.com All: email@example.com other@domain.com
原理
FindStringFindAllStringRegexpFindStringFindAllString
RegexpFindXXXregexpMustCompile