go正则表达式分组匹配,如何在Golang正则表达式中捕获组功
能?
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:
`(?\d{4})-(?\d{2})-(?\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\d{4})-(?P\d{2})-(?P\d{2})
Cross reference capture group names with re.SubexpNames().
package main
import (
"fmt"
"regexp"
)
reference groupfunc main() {
r := regexp.MustCompile(`(?P\d{4})-(?P\d{2})-(?P\d{2})`)
fmt.Printf("%#v\n", r.FindStringSubmatch(`2015-05-27`))
fmt.Printf("%#v\n", r.SubexpNames())
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。