gpt4 book ai didi

go - FindStringSubmatch 两次返回匹配组

转载 作者:IT王子 更新时间:2023-10-29 02:05:44 26 4
gpt4 key购买 nike

也许我遗漏了一些关于 go 的 regexp.FindStringSubmatch() 的非常基本的东西。我想捕获包含字符串 "Serial Number: " 之后的所有数字的组,但得到意外的输出。我的代码如下:

package main
import "fmt"
import "regexp"

func main() {

x := "Serial Number: 12334"
r := regexp.MustCompile(`(\d+)`)
res := r.FindStringSubmatch(x)

for i,val := range res {
fmt.Printf("entry %d:%s\n", i,val)
}
}

输出是:

entry 0:12334
entry 1:12334

我更熟悉 python 的分组,它看起来非常简单:

>>> re.search('(\d+)', "Serial Number: 12344").groups()[0]
'12344'

如何让分组在 go 中工作?谢谢

最佳答案

来自 Regexp.FindStringSubmatch :

FindStringSubmatch returns a slice of strings holding the text of the leftmost match of the regular expression in s and the matches

所以:

  • 第一个条目是匹配的:'12334'(最左边的匹配)
  • 第二个条目是一个捕获组:'12334'

另一个例子:

re := regexp.MustCompile("a(x*)b(y|z)c")
fmt.Printf("%q\n", re.FindStringSubmatch("-axxxbyc-"))

那会打印:

  • 最左边的匹配项:"axxxbyc"
  • 捕获的两个组:"xxx""y"

关于go - FindStringSubmatch 两次返回匹配组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26936396/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com