正则基础
符号 | 描述 | 示例 |
---|---|---|
^ | 匹配字符串的开始位置 | ^http:http(true),thttp(false) |
$ | 匹配字符串的结束位置 | http&:http(true),https(false) |
+ | 匹配前面子表达式一次或者多次,匹配字符+,使用+ | abc+:abcabc(true),acc(false) |
? | 匹配前面子表达式0次或者1次,匹配字符?使用? | (abc)?:abc(true) ,acc(true) |
| | 指明两项之间的选择,匹配|使用\| | (a|b) :a(true) ,c(false) |
. | 匹配除换行符 \n 之外的任何单字符。要匹配 . ,请使用 . | (.):a(true),\n(false) |
匹配手机号
func main() {
reg := "^1\\d{10}$" // 1开头,后接10位数字
rgx, err := regexp.Compile(reg)
if (err != nil) {
fmt.Println("正则表达式不合法")
}
fmt.Println(rgx.MatchString("13993212345"))
fmt.Println(rgx.MatchString("01111111111"))
}
输出
true
false
匹配车牌号
func main() {
testStrYes := "京A12345"
testStrNo := "鲁A12D4"
fmt.Println(testStrYes, "匹配结果:", MatchPlateNo(testStrYes))
fmt.Println(testStrNo, "匹配结果:", MatchPlateNo(testStrNo))
}
func MatchPlateNo(plateNo string) bool {
pattern := "^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{1}[a-zA-Z]{1}[a-zA-Z0-9]{5,6}$"
res, err := regexp.MatchString(pattern, plateNo)
return err == nil && res
}
输出
京A12345 匹配结果: true
鲁A12D4 匹配结果: false
匹配网页链接
func main() {
testStrYes := "http://www.baidu.com"
testStrNo := "https:// www.baidu.com"
fmt.Println(testStrYes, "匹配结果:", MatchHttpUrl(testStrYes))
fmt.Println(testStrNo, "匹配结果:", MatchHttpUrl(testStrNo))
}
func MatchHttpUrl(str string) bool {
pattern := "^http[s]{0,1}:\\/\\/\\S+$"
res, err := regexp.MatchString(pattern, str)
return err == nil && res
}
输出
http://www.baidu.com 匹配结果: true
https:// www.baidu.com 匹配结果: false
匹配正负整数、正负小数
package main
import "fmt"
import "regexp"
func main() {
testStrYes := "3.1415926"
testStrNo := "003"
fmt.Println(testStrYes, "匹配结果:", MatchNumberWithPoint(testStrYes))
fmt.Println(testStrNo, "匹配结果:", MatchNumberWithPoint(testStrNo))
}
func MatchNumberWithPoint(str string) bool {
pattern := "^-?(0|([1-9][0-9]*))([\\.][0-9]+)?$"
res, err := regexp.MatchString(pattern, str)
return err == nil && res
}
输出
3.1415926 匹配结果: true
003 匹配结果: false