How to get capturing group functionality in Go regular expressions

前端 未结 5 979
闹比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条回答
  •  萌比男神i
    2020-12-04 22:04

    I had created a function for handling url expressions but it suits your needs too. You can check this snippet but it simply works like this:

    /**
     * Parses url with the given regular expression and returns the 
     * group values defined in the expression.
     *
     */
    func getParams(regEx, url string) (paramsMap map[string]string) {
    
        var compRegEx = regexp.MustCompile(regEx)
        match := compRegEx.FindStringSubmatch(url)
    
        paramsMap = make(map[string]string)
        for i, name := range compRegEx.SubexpNames() {
            if i > 0 && i <= len(match) {
                paramsMap[name] = match[i]
            }
        }
        return
    }
    

    You can use this function like:

    params := getParams(`(?P\d{4})-(?P\d{2})-(?P\d{2})`, `2015-05-27`)
    fmt.Println(params)
    

    and the output will be:

    map[Year:2015 Month:05 Day:27]
    

提交回复
热议问题