如何在Golang正则表达式中捕获组功能? [英] How to get capturing group functionality in Golang regular expressions?
问题描述
我从Ruby to Go移植一个库,刚刚发现Ruby中的正则表达式与Go(google RE2)不兼容。我注意到Ruby& Java(加上其他语言使用PCRE正则表达式(Perl兼容,支持捕获组)),所以我需要重写我的表达式,以便它们在Go中编译成功。
<例如,我有以下正则表达式:
`(?< Year> \d {4}) - (?< Month> \d {2}) - (?< Day> \d {2})`
这应该接受以下输入:
2001-01-20
捕获组允许将年,月和日捕获到变量中。为了获得每个组的价值,这很容易;您只需使用组名称将返回的匹配数据编入索引并将值返回。所以,例如为了得到年份,就像这样的伪代码:
m = expression.Match(2001-01- 20)
year = m [Year]
这是我使用的模式很多我的表达式,所以我有很多重写要做。
那么,有没有办法在Go regexp中获得这种功能;我应该如何重写这些表达式?
我应该如何重写这些表达式?
按照这里:
(?P
使用 re.SubexpNames()
。
交叉引用捕获组名称并使用如下:
<$ c
$ f
$ b $ func main(){$ b $ (?P< Year> \d {4}) - (?Pfmt.Printf(%#v\\\
,r.FindStringSubmatch(`2015-05-27`))
fmt.Printf(%#v\\\
,r。 SubexpNames())
}
I'm porting a library from Ruby to Go, and have just discovered that regular expressions in Ruby are not compatible with Go (google RE2). It's come to my attention that Ruby & Java (plus other languages use PCRE regular expressions (perl compatible, which supports capturing groups)), so I need to re-write my expressions so that they compile ok in Go.
For example, I have the following regex:
`(?<Year>\d{4})-(?<Month>\d{2})-(?<Day>\d{2})`
This should accept input such as:
2001-01-20
The capturing groups allow the year, month and day to be captured into variables. To get the value of each group, it's very easy; you just index into the returned matched data with the group name and you get the value back. So, for example to get the year, something like this pseudo code:
m=expression.Match("2001-01-20")
year = m["Year"]
This is a pattern I use a lot in my expressions, so I have a lot of re-writing to do.
So, is there a way to get this kind of functionality in Go regexp; how should I re-write these expressions?
how should I re-write these expressions?
Add some Ps, as defined here:
(?P<Year>\d{4})-(?P<Month>\d{2})-(?P<Day>\d{2})
Cross reference capture group names with re.SubexpNames()
.
And use as follows:
package main
import (
"fmt"
"regexp"
)
func main() {
r := regexp.MustCompile(`(?P<Year>\d{4})-(?P<Month>\d{2})-(?P<Day>\d{2})`)
fmt.Printf("%#v\n", r.FindStringSubmatch(`2015-05-27`))
fmt.Printf("%#v\n", r.SubexpNames())
}
这篇关于如何在Golang正则表达式中捕获组功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!