Go语言实用库01——正则表达式

Go语言中的正则表达式

一、正则表达式匹配

1.1 匹配单个子串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const str = "my email is sherlockjgy@gmail.com"

func main() {
// 正则表达式规则声明,解析正则表达式
// 返回Regexp对象,用于后续操作
compile, err := regexp.Compile(`[A-Za-z0-9]+@[A-Za-z0-9]+\.[A-Za-z0-9]+`)
if err != nil {
panic("你的正则表达式存在语法错误!")
}
// 从目标字符串当中查找是否存在符合正则表达式规则的字符子串
// 返回true or false
isMatch := compile.MatchString(str)
fmt.Printf("目标字符串中是否存在符合规则的子串:%v\n", isMatch) // true

// 从目标字符串当中查找并返回符合正则表达式规则的字符子串
// 若不存在,则返回空串
matchString := compile.FindString(str)
fmt.Println(matchString) // sherlockjgy@gmail.com
}

提醒:建议将正则表达式规则书写在【`】引号(键盘1左边的按键)中,这样Go语言不会解析表达式中的转义字符,否则每个斜杠都需要双斜杠代替

1.2 匹配多个子串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const str = `my email are sherlockjgy@gmail.com
and shelockgy@live.com`

func main() {
// 正则表达式规则声明,解析正则表达式
// 返回Regexp对象,用于后续操作
compile, err := regexp.Compile(`[A-Za-z0-9]+@[A-Za-z0-9]+\.[A-Za-z0-9]+`)
if err != nil {
panic("你的正则表达式存在语法错误!")
}

// 从目标字符串当中查找并返回【多个】符合正则表达式规则的字符子串
// 第二个参数代表需要查询多少个符合要求的子串,-1代表查询所有
matchString := compile.FindAllString(str, -1)
fmt.Println(matchString, len(matchString)) // [sherlockjgy@gmail.com shelockgy@live.com] 2
}

1.3 字符串匹配并分组

在正则表达式中运用小括号,可以对被匹配成功对子串进行分组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const str = `my email are sherlockjgy@gmail.com
and shelockgy@live.com
and helloworld@test.com.cn`

func main() {
// 正则表达式规则声明,解析正则表达式
// 返回Regexp对象,用于后续操作
compile, err := regexp.Compile(`([A-Za-z0-9]+)@([A-Za-z0-9]+)([.A-Za-z0-9]+)`)
if err != nil {
panic("你的正则表达式存在语法错误!")
}

// 返回一个二维数组
matchString := compile.FindAllStringSubmatch(str, -1)
for _, value := range matchString {
fmt.Println(value)
}
}

输出:

1
2
3
[sherlockjgy@gmail.com sherlockjgy gmail .com]
[shelockgy@live.com shelockgy live .com]
[helloworld@test.com.cn helloworld test .com.cn]