How to get capturing group functionality in Go regular expressions

前端 未结 5 974
闹比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:15

    Simple way to determine group names based on @VasileM answer.

    Disclaimer: it's not about memory/cpu/time optimization

    package main
    
    import (
        "fmt"
        "regexp"
    )
    
    func main() {
        r := regexp.MustCompile(`^(?P\d{4})-(?P\d{2})-(?P\d{2})$`)
    
        res := r.FindStringSubmatch(`2015-05-27`)
        names := r.SubexpNames()
        for i, _ := range res {
            if i != 0 {
                fmt.Println(names[i], res[i])
            }
        }
    }
    

    https://play.golang.org/p/Y9cIVhMa2pU

提交回复
热议问题