当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > Go语言正则表达式的使用详解

Go语言正则表达式的使用详解

2020年06月23日  | 移动技术网IT编程  | 我要评论

正则表达式是一种进行模式匹配和文本操纵的功能强大的工具。正则表达式灵活、易用,按照它的语法规则,随需构造出的匹配模式就能够从原始文本中筛选出几乎任何你想要得到的字符组合。

准则

  • 默认是最短匹配,只要字符串满足条件就返回。
  • 如果没有匹配到,都是返回为nil。
  • 如果需要做最长匹配,调用longest()函数。
  • 正则表达式功能:匹配(macth),查找(find)和替换(replace)。
  • 存在长度选择的函数,传入<0的数字表示匹配全部。

使用regexp调用

match,matchreader和 matchstring

// 判断b中是够包含pattern能够组成的任意字符串
func match(pattern string, b []byte) (matched bool, err error)

// 判断reader r中返回的字符串是否包含pattern能够组成的任意字符串
func matchreader(pattern string, r io.runereader) (matched bool, err error)

// 判断字符串s中是否包含pattern能够组成的任意字符串
func matchstring(pattern string, s string) (matched bool, err error)

compile 和 mushcompile

func compile(expr string) (*regexp, error)
func mustcompile(str string) *regexp

compile :返回 regexp 对象,方便调用指针函数。

mustcompile :同compile,解析表达式失败,会panic。

在匹配文本时,该正则表达式会尽可能早的开始匹配,并且在匹配过程中选择回溯搜索到的第一个匹配结果。这种模式被称为 leftmost-first ,另外一般情况下使用 mustcompile 即可。

使用regexp.regexp对象来调用

find 和 findall

  • func (re *regexp) find(b []byte) []byte
  • func (re *regexp) findall(b []byte, n int) [][]byte

find返回保管正则表达式re在b中的最左侧的一个匹配结果的[]byte切片。如果没有匹配到,会返回nil,最多匹配一个。

re := regexp.mustcompile(`foo.?`)
fmt.printf("%q\n", re.find([]byte(`seafood fool`)))
re := regexp.mustcompile(`foo.?`)
fmt.printf("%q\n", re.findall([]byte(`seafood fool`), -1))

findall 功能与 find 一样,只是返回全部满足条件的数据。

findstring 和 findallstring

  • func (re *regexp) findstring(s string) string
  • func (re *regexp) findallstring(s string, n int) []string

与 find 和 findall 一样,只是针对字符串string操作。

findindex 和 findallindex

  • func (re *regexp) findindex(b []byte) (loc []int)
  • func (re *regexp) findallindex(b []byte, n int) [][]int

findindex , 返回 b 中满足匹配字符串部分的起始位置,同样是**“leftmost-first”**原则,loc包含起止位置。如果没有找到,直接返回 nil 。

findallindex ,功能和 findindex 保持一致,只是匹配多个, n 决定了匹配的位置。

findstringindex 和 findallstringindex

  • func (re *regexp) findstringindex(s string) (loc []int)
  • func (re *regexp) findallstringindex(s string, n int) [][]int

与 findindex 和 findallindex 使用方式类似,只是针对的是字符串string。

findstringsubmatch 和 findallstringsubmatch

  • func (re *regexp) findstringsubmatch(s string) []string

findstringsubmatch :采用左匹配原则,最多匹配一个,如果没有的话,返回 nil 。对于返回的 []string ,分别标示匹配的字符串,子串。

re := regexp.mustcompile(`a(x*)b(y|z)c`)
fmt.printf("%q\n", re.findstringsubmatch("-axxxbyc-"))
fmt.printf("%q\n", re.findstringsubmatch("-abzc-"))

输出结果:

["axxxbyc" "xxx" "y"]
["abzc" "" "z"]

  • func (re *regexp) findallstringsubmatch(s string, n int) [][]string

和 findstringsubmatch 使用类似,只是能顾选择匹配的长度, -1 表示匹配到末尾。

re := regexp.mustcompile(`a(x*)b`)
fmt.printf("%q\n", re.findallstringsubmatch("-ab-", -1))
fmt.printf("%q\n", re.findallstringsubmatch("-axxb-", -1))
fmt.printf("%q\n", re.findallstringsubmatch("-ab-axb-", -1))
fmt.printf("%q\n", re.findallstringsubmatch("-axxb-ab-", -1))

输出结果:

[["ab" ""]]
[["axxb" "xx"]]
[["ab" ""] ["axb" "x"]]
[["axxb" "xx"] ["ab" ""]]

findsubmatchindex 和 findallsubmatchindex

  • func (re *regexp) findsubmatchindex(b []byte) []int
  • func (re *regexp) findallsubmatchindex(b []byte, n int) [][]int 计算子串在源串中的位置,已经存在 (x*) 等返回结果处理,如果没有返回 nil 。

另外, index 返回为 左闭右开 的模式,示例中的 2,2 表示空字符串的意思。 并且,不会存在重合匹配的,比如说"-axxb-ab-"去匹配 a(x*)b ,不会存在第一个 a 和最后一个 b 结合的情况,如果使用 longest 就会匹配最长的。

re := regexp.mustcompile(`a(x*)b`)
// indices:
// 01234567 012345678
// -ab-axb- -axxb-ab-
fmt.println(re.findallstringsubmatchindex("-ab-", -1))
fmt.println(re.findallstringsubmatchindex("-axxb-", -1))
fmt.println(re.findallstringsubmatchindex("-ab-axb-", -1))
fmt.println(re.findallstringsubmatchindex("-axxb-ab-", -1))
fmt.println(re.findallstringsubmatchindex("-foo-", -1))

输出结果:

[[1 3 2 2]] // 2 2 表示为空
[[1 5 2 4]]
[[1 3 2 2] [4 7 5 6]]
[[1 5 2 4] [6 8 7 7]]
[]


findstringsubmatchindex 和 findallstringsubmatchindex
func (re *regexp) findstringsubmatchindex(s string) []int
func (re *regexp) findallstringsubmatchindex(s string, n int) [][]int
和 findsubmatchindex , findallsubmatchindex 保持一致。

longest
func (re *regexp) longest() 获取最长匹配的满足条件的内容。
re := regexp.mustcompile(`a(|b)`)
fmt.println(re.findstring("ab"))
re.longest()
fmt.println(re.findstring("ab"))

输出结果:

a
ab

下面这种情况不会最长匹配。

re := regexp.mustcompile(`a(x*)b`)
re.longest()
fmt.println(re.findstring("-axxb-ab-")) // axxb,不会存在第一个a和最后一个b组合的过程。

match,matchstring和matchreader

  • func (re *regexp) match(b []byte) bool
  • func (re *regexp) matchstring(s string) bool
  • func (re *regexp) matchreader(r io.runereader) bool

判断 b , s 和 r 返回的数据是否满足正则表达式,返回 true 或者 false 。

numsubexp

  • func (re *regexp) numsubexp() int

返回分组的数量。

re0 := regexp.mustcompile(`a.`)
fmt.printf("%d\n", re0.numsubexp())

re := regexp.mustcompile(`(.*)((a)b)(.*)a`)
fmt.println(re.numsubexp())

输出结果:

0
4

replaceall 和 replaceallstring
func (re *regexp) replaceall(src, repl []byte) []byte
func (re *regexp) replaceallstring(src, repl string) string
replaceallstring 与 replaceall 使用方式相同。

re := regexp.mustcompile(`a(x*)b`)
fmt.printf("%s\n", re.replaceall([]byte("-ab-axxb-"), []byte("t"))) 
fmt.printf("%s\n", re.replaceall([]byte("-ab-axxb-"), []byte("$1"))) // $1表示匹配的第一个子串,这是ab的中间无字符串,所以$1为空,然后使用空去替换满足正则表达式的部分。
fmt.printf("%s\n", re.replaceall([]byte("-ab-axxb-"), []byte("$1w"))) // "$1w"等价与"$(1w)",值为空,将满足条件的部分完全替换为空。
fmt.printf("%s\n", re.replaceall([]byte("-ab-axxb-"), []byte("${1}w"))) // ${1}匹配(x*),保留。输出-w-xxw-

输出结果:

-t-t-
--xx-
---
-w-xxw-

s := "hello world, 123 go!"
//定义一个正则表达式reg,匹配hello或者go
reg := regexp.mustcompile(`(hell|g)o`)

s2 := "2019-12-01,test"
//定义一个正则表达式reg2,匹配 yyyy-mm-dd 的日期格式
reg2 := regexp.mustcompile(`(\d{4})-(\d{2})-(\d{2})`)

//最简单的情况,用“t替换”"-ab-axxb-"中符合正则"a(x*)b"的部分
reg3 := regexp.mustcompile("a(x*)b")
fmt.println(re.replaceallstring("-ab-axxb-", "t")) // -t-t-

//${1}匹配"hello world, 123 go!"中符合正则`(hell|g)`的部分并保留,去掉"hello"与"go"中的'o'并用"ddd"追加
rep1 := "${1}ddd"
fmt.printf("%q\n", reg.replaceallstring(s, rep1)) // hellddd world, 123 gddd!

//首先,"2019-12-01,test"中符合正则表达式`(\d{4})-(\d{2})-(\d{2})`的部分是"2019-12-01",将该部分匹配'(\d{4})'的'2019'保留,去掉剩余部分
rep2 := "${1}"
fmt.printf("%q\n", reg2.replaceallstring(s2,rep2)) // 2019,test

//首先,"2019-12-01,test"中符合正则表达式`(\d{4})-(\d{2})-(\d{2})`的部分是"2019-12-01",将该部分匹配'(\d{2})'的'12'保留,去掉剩余部分
 rep3 := "${2}"
fmt.printf("%q\n", reg2.replaceallstring(s2,rep3)) // 12,test

//首先,"2019-12-01,test"中符合正则表达式`(\d{4})-(\d{2})-(\d{2})`的部分是"2019-12-01",将该部分匹配'(\d{2})'的'01'保留,去掉剩余部分,并追加"13:30:12"
rep4 := "${3}:13:30:12"
fmt.printf("%q\n", reg2.replaceallstring(s2,rep4)) // 01:13:30:12,test
}

replaceallfunc 和 replaceallstringfunc

  • func (re *regexp) replaceallfunc(src []byte, repl func([]byte) []byte) []byte
  • func (re *regexp) replaceallstringfunc(src string, repl func(string) string) string

将匹配出来满足条件的 []byte 作为参数传入函数中。

re := regexp.mustcompile(`[^aeiou]`)
fmt.println(re.replaceallstringfunc("seafood fool", strings.toupper))

两者使用方式类似。

replaceallliteral 和 replaceallliteralstring

  • func (re *regexp) replaceallliteral(src, repl []byte) []byte
  • func (re *regexp) replaceallliteralstring(src, repl string) string

匹配字面常量,不转换。

re := regexp.mustcompile(`a(x*)b`)
fmt.println(re.replaceallliteralstring("-ab-axxb-", "t"))
fmt.println(re.replaceallliteralstring("-ab-axxb-", "$1"))
fmt.println(re.replaceallliteralstring("-ab-axxb-", "${1}"))

输出结果:

-t-t-
-$1-$1-
-${1}-${1}-

关于 $1 说明:

expand 和 expandstring

  • func (re *regexp) expand(dst []byte, template []byte, src []byte, match []int) []byte
  • func (re *regexp) expandstring(dst []byte, template string, src string, match []int) []byte

expand返回新生成的将template添加到dst后面的切片。在添加时,expand会将template中的变量替换为从src匹配的结果。match应该是被findsubmatchindex返回的匹配结果起止位置索引。(通常就是匹配src,除非你要将匹配得到的位置用于另一个[]byte)

在template参数里,一个变量表示为格式如: $name 或 ${name} 的字符串,其中name是长度>0的字母、数字和下划线的序列。一个单纯的数字字符名如$1会作为捕获分组的数字索引;其他的名字对应(?p...)语法产生的命名捕获分组的名字。超出范围的数字索引、索引对应的分组未匹配到文本、正则表达式中未出现的分组名,都会被替换为空切片。

$name格式的变量名,name会尽可能取最长序列: $1x 等价于 ${1x} 而非 ${1}x , $10 等价于 ${10} 而非 ${1}0 。因此 $name 适用在后跟空格/换行等字符的情况, ${name} 适用所有情况。

如果要在输出中插入一个字面值 '$' ,在template里可以使用 $$ 。

其他示例

解析网址

flysnowregexp := regexp.mustcompile(`^http://www.flysnow.org/([\d]{4})/([\d]{2})/([\d]{2})/([\w-]+).html$`)
params := flysnowregexp.findstringsubmatch("http://www.flysnow.org/2018/01/20/golang-goquery-examples-selector.html")
// 返回[]string{}数据类型
for _, param := range params {
 fmt.println(param)
}

输出结果:


2018
01
20
golang-goquery-examples-selector

总结

到此这篇关于go语言正则表达式的使用详解的文章就介绍到这了,更多相关go正则表达式使用内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网