How to get capturing group functionality in Go regular expressions

前端 未结 5 986
闹比i
闹比i 2020-12-04 21:47

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 Ru

5条回答
  •  臣服心动
    2020-12-04 22:00

    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().

    And use as follows:

    package main
    
    import (
        "fmt"
        "regexp"
    )
    
    func 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())
    }
    

提交回复
热议问题