1. golang中的正则表达式包
golang提供了内置的regexp包,用于处理正则表达式操作。该包提供正则表达式对象,可以执行各种文本操作,如匹配、查找和替换。

golang中的regexp包提供了一组函数和类型,用于处理正则表达式。以下是一些常用的函数:
- regexp.compile : 编译正则表达式,返回正则对象。
- regexp.match : 判断文本是否与正则表达式匹配。
- regexp.findstring : 查找并返回第一个匹配的字符串。
- regexp.findallstring : 查找并返回所有匹配的字符串。
- regexp.replaceallstring : 替换所有匹配的字符串。
2. 正则表达式语法简述
在使用正则表达式时,了解其语法规则至关重要。以下是一些常用的正则表达式元字符及其含义:
.: 匹配任意字符,除了换行符。*: 匹配前一个字符零次或多次。+: 匹配前一个字符一次或多次。?: 匹配前一个字符零次或一次。\d: 匹配数字字符。\w: 匹配字母、数字或下划线。[]: 字符集,匹配括号内的任意一个字符。
3. 相关示例
邮箱匹配
package main
import (
"fmt"
"regexp"
)
func main() {
text := "邮箱是 demo@qq.com 。"
re := regexp.mustcompile(`[a-za-z0-9._%+-]+@[a-za-z0-9.-]+\.[a-za-z]{2,4}`)
matches := re.findstringsubmatch(text)
if len(matches) > 0 {
fmt.println("匹配的邮箱地址:", matches[0])
}
}
匹配 url
text := "这是一个链接文本:https://www.163.com 和 https://www.google.com"
re := regexp.mustcompile(`https?://[^\s]+`)
matches := re.findallstring(text, -1)
for _, match := range matches {
fmt.println("匹配的链接:", match)
}
数字、汉字、拼音的匹配
reg1 := regexp.mustcompile(`[0-9]+`) //正则 匹配数字
reg2 := regexp.mustcompile(`[\p{han}]+`) //正则 匹配汉字
reg3 := regexp.mustcompile(`[a-z]+`) //正则 匹配拼音
通过 find 匹配(传入[]byte,返回[]byte)
//----------- find 使用 -----------------//
str := "ab001234hah120210a880218end"
reg := regexp.mustcompile("\\d{6}") //六位连续的数字
// 返回str中第一个匹配reg的字符串
data := reg.find([]byte(str))
fmt.println(string(data))
//----------- findall 使用 ---------------//
//返回 str中所有匹配reg的字符串, 第二个参数表示最多返回的个数,传-1表示返回所有结果
dataslice := reg.findall([]byte(str), -1)
for _, v := range dataslice {
fmt.println(string(v))
}
findindex 获取索引位
//------------- findindex ----------------//
str := "00start123endhahastart120psend09start10000end"
// 返回第一个匹配的字符串的首末位置
reg := regexp.mustcompile("start\\d*end") //start开始,end结束,中间全是数字
// index[0]表示开始位置,index[1]表示结束位置
index := reg.findindex([]byte(str))
fmt.println("start:", index[0], ",end:", index[1], str[index[0]:index[1]])
//------------- findallindex ----------------//
// 返回所有匹配的字符串首末位置
indexslice := reg.findallindex([]byte(str), -1)
for _, v := range indexslice {
fmt.println("start:", v[0], ",end:", v[1], str[v[0]:v[1]])
}
findstring 操作更方便
//-----------findstring 和 findallstring ----------------//
str := "ab001234hah120210a880218end"
reg := regexp.mustcompile("\\d{6}") //六位连续的数字
fmt.println(reg.findstring(str))
fmt.println(reg.findallstring(str, -1))
// 以下两个方法是类似的,获取索引位
fmt.println(reg.findstringindex(str))
fmt.println(reg.findindex([]byte(str)))
// 查找汉字
str1 := "hello中国hello世界和平hi好"
reg1 := regexp.mustcompile("[\\p{han}]+")
fmt.println(reg1.findallstring(str1, -1)) // [中国 世界和平 好]
// 查找数字或小写字母
str2 := "haha00azbapabc09fgabhy99"
reg2 := regexp.mustcompile("[\\d|a-z]+")
fmt.println(reg2.findallstring(str2, -1)) // [00az abc09 ab 99]
//----------- replaceallstring ----------------//
// 查找并替换
str3 := "welcome for beijing-tianjin crh train"
reg3 := regexp.mustcompile(" ")
fmt.println(reg.replaceallstring(str3, "@")) //将空格替换为@字符
// welcome@for@beijing-tianjin@crh@train
常用匹配
text := `hello 世界!123 go.`
// 查找连续的小写字母
reg := regexp.mustcompile(`[a-z]+`)
fmt.printf("%q\n", reg.findallstring(text, -1) // 输出结果["ello" "o"]
// 查找连续的非小写字母
reg = regexp.mustcompile(`[^a-z]+`)
fmt.printf("%q\n", reg.findallstring(text, -1)) // ["h" " 世界!123 g" "."]
// 查找连续的单词字母
reg = regexp.mustcompile(`[\w]+`)
fmt.printf("%q\n", reg.findallstring(text, -1)) // ["hello" "123" "go"]
// 查找连续的非单词字母、非空白字符
reg = regexp.mustcompile(`[^\w\s]+`)
fmt.printf("%q\n", reg.findallstring(text, -1)) // ["世界!" "."]
// 查找连续的大写字母
reg = regexp.mustcompile(`[[:upper:]]+`)
fmt.printf("%q\n", reg.findallstring(text, -1)) // ["h" "g"]
// 查找连续的非 ascii 字符
reg = regexp.mustcompile(`[[:^ascii:]]+`)
fmt.printf("%q\n", reg.findallstring(text, -1)) // ["世界!"]
// 查找连续的标点符号
reg = regexp.mustcompile(`[\pp]+`)
fmt.printf("%q\n", reg.findallstring(text, -1)) // ["!" "."]
// 查找连续的非标点符号字符
reg = regexp.mustcompile(`[\pp]+`)
fmt.printf("%q\n", reg.findallstring(text, -1)) // ["hello 世界" "123 go"]
// 查找连续的汉字
reg = regexp.mustcompile(`[\p{han}]+`)
fmt.printf("%q\n", reg.findallstring(text, -1)) // ["世界"]
// 查找连续的非汉字字符
reg = regexp.mustcompile(`[\p{han}]+`)
fmt.printf("%q\n", reg.findallstring(text, -1)) // ["hello " "!123 go."]
// 查找 hello 或 go
reg = regexp.mustcompile(`hello|go`)
fmt.printf("%q\n", reg.findallstring(text, -1)) // ["hello" "go"]
// 查找行首以 h 开头,以空格结尾的字符串
reg = regexp.mustcompile(`^h.*\s`)
fmt.printf("%q\n", reg.findallstring(text, -1)) // ["hello 世界!123 "]
// 查找行首以 h 开头,以空白结尾的字符串(非贪婪模式)
reg = regexp.mustcompile(`(?u)^h.*\s`)
fmt.printf("%q\n", reg.findallstring(text, -1)) // ["hello "]
// 查找以 hello 开头(忽略大小写),以 go 结尾的字符串
reg = regexp.mustcompile(`(?i:^hello).*go`)
fmt.printf("%q\n", reg.findallstring(text, -1)) // ["hello 世界!123 go"]
// 查找 go.
reg = regexp.mustcompile(`\qgo.\e`)
fmt.printf("%q\n", reg.findallstring(text, -1)) // ["go."]
// 查找从行首开始,以空格结尾的字符串(非贪婪模式)
reg = regexp.mustcompile(`(?u)^.* `)
fmt.printf("%q\n", reg.findallstring(text, -1)) // ["hello "]
// 查找以空格开头,到行尾结束,中间不包含空格字符串
reg = regexp.mustcompile(` [^ ]*$`)
fmt.printf("%q\n", reg.findallstring(text, -1)) // [" go."]
// 查找“单词边界”之间的字符串
reg = regexp.mustcompile(`(?u)\b.+\b`)
fmt.printf("%q\n", reg.findallstring(text, -1)) // ["hello" " 世界!" "123" " " "go"]
// 查找连续 1 次到 4 次的非空格字符,并以 o 结尾的字符串
reg = regexp.mustcompile(`[^ ]{1,4}o`)
fmt.printf("%q\n", reg.findallstring(text, -1)) // ["hello" "go"]
// 查找 hello 或 go
reg = regexp.mustcompile(`(?:hell|g)o`)
fmt.printf("%q\n", reg.findallstring(text, -1)) // ["hello" "go"]
// 查找 hello 或 go,替换为 hellooo、gooo
reg = regexp.mustcompile(`(?phell|g)o`)
fmt.printf("%q\n", reg.replaceallstring(text, "${n}ooo")) // "hellooo 世界!123 gooo."
// 交换 hello 和 go
reg = regexp.mustcompile(`(hello)(.*)(go)`)
fmt.printf("%q\n", reg.replaceallstring(text, "$3$2$1")) // "go 世界!123 hello."
reg = regexp.mustcompile(`[\f\t\n\r\v\123\x7f\x{10ffff}\\\^\$\.\*\+\?\{\}\(\)\[\]\|]`)
fmt.printf("%q\n", reg.replaceallstring("\f\t\n\r\v\123\x7f\u0010ffff\\^$.*+?{}()[]|", "-"))
4. 总结
在golang中,使用regexp包可以轻松实现各种文本操作。无论是从文本中提取信息还是进行验证,正则表达式都是编程中不可或缺的一部分。
到此这篇关于golang中正则表达式语法及相关示例的文章就介绍到这了,更多相关golang正则表达式内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论