Getting Capturing Group Functionality in Go Regular Expressions
Regular expressions in Go (using the google RE2 library) differ from those in Ruby that support capturing groups. Therefore, when porting code from Ruby, it becomes necessary to rewrite regular expressions to be compatible with Go.
For example, consider the Ruby regular expression:
(?<Year>\d{4})-(?<Month>\d{2})-(?<Day>\d{2})
This expression captures the year, month, and day into named capturing groups, allowing easy retrieval. To achieve similar functionality in Go, add some Ps as defined in the following:
(?P<Year>\d{4})-(?P<Month>\d{2})-(?P<Day>\d{2})
Cross-reference the capture group names with re.SubexpNames():
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()) }
The above is the detailed content of How Can I Replicate Ruby's Named Capturing Groups in Go Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!