也许我遗漏了一些关于 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)
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
entry 0:12334
entry 1:12334
Run Code Online (Sandbox Code Playgroud)
我更熟悉 python 的分组,它看起来非常简单:
>>> re.search('(\d+)', "Serial Number: 12344").groups()[0]
'12344'
Run Code Online (Sandbox Code Playgroud)
我怎样才能让分组在 go 中工作?谢谢
FindStringSubmatch返回一个字符串切片,其中包含 s 中正则表达式最左边匹配的文本以及匹配项
所以:
12334”(最左边的匹配)12334”另一个例子:
re := regexp.MustCompile("a(x*)b(y|z)c")
fmt.Printf("%q\n", re.FindStringSubmatch("-axxxbyc-"))
Run Code Online (Sandbox Code Playgroud)
那会打印:
"axxxbyc""xxx" "y"