go语言中常用的功能之四(正则匹配)

go语言中正则匹配与替换

1. 匹配字符串是否符合规则

使用MustCompile函数,会抛出一个致命错误,导致程序退出,不会执行 deferrecover 函数,当然这也是为了检查匹配表达式的正确性,在写代码的时候抛出来更好

1.1 验证手机号

str := "1371245784"
//正则匹配手机号
pattern := "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$"
re := regexp.MustCompile(pattern) //确保正则表达式的正确 遇到错误会直接panic
match := re.MatchString(str)
if !match {
	fmt.Println("wrong phone number ")
	return 
}
fmt.Println(match) //true

1.2 验证邮箱

str := `[email protected]`
pattern := "^[A-Za-z0-9]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$"
re := regexp.MustCompile(pattern) 
match := re.MatchString(str)
if !match {
	fmt.Println("wrong email ")
	return 
}
fmt.Println(match) //true

1.3 验证中文

pattern := "[\u4e00-\u9fa5]"

2. 提取匹配结果

正则解析apache访问日志

//127.0.0.1 - - [08/Jan/2019:15:17:18 +0800] "GET /test/index/aa HTTP/1.1" 200 107675
//127.0.0.1 - - [10/Jan/2019:11:38:23 +0800] "GET /favicon.ico HTTP/1.1" 404 2236

// (\d+\.\d+\.\d+\.\d+) - - \[(.*?)\/(.*?)\/(.*?) .*\] "(\w+) (\/.*?) (.*?)" (\d+) (\d+)$
str := `127.0.0.1 - - [10/Jan/2019:11:38:23 +0800] "GET /favicon.ico HTTP/1.1" 404 2236`
pattern := `^(\d+\.\d+\.\d+\.\d+) - - \[(.*?)\/(.*?)\/(.*?) .*\] "(\w+) (\/.*?) (.*?)" (\d+) (\d+)$`
re := regexp.MustCompile(pattern) //确保正则表达式的正确 遇到错误会直接panic
match := re.MatchString(str)
fmt.Println(match)
matchArr := re.FindStringSubmatch(str)
for _,v := range matchArr{
	fmt.Println(v)
}

打印结果:
true
127.0.0.1 - - [10/Jan/2019:11:38:23 +0800] “GET /favicon.ico HTTP/1.1” 404 2236
127.0.0.1
10
Jan
2019:11:38:23
GET
/favicon.ico
HTTP/1.1
404
2236

3. 正则替换匹配值

将手机号中间4位替换为 ****

str := `13734351278`
pattern := `^(\d{3})(\d{4})(\d{4})$`
re := regexp.MustCompile(pattern) //确保正则表达式的正确 遇到错误会直接panic
match := re.MatchString(str)
if !match {
	fmt.Println("phone number error")
	return
}
repStr := re.ReplaceAllString(str,"$1****$3")
fmt.Println(repStr) //137****1278

猜你喜欢

转载自blog.csdn.net/wujiangwei567/article/details/86593396