go正则匹配

正则基础

符号描述示例
^匹配字符串的开始位置^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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值