62

I'm coming from Python, so I'm probably just not looking at this the right way. I'd like to create a fairly complicated regex and be able to access the fields match by name. I can't seem to find a good example. The closest I've managed to get is this:

package main

import (
  "fmt"
  "regexp"
)

var myExp = regexp.MustCompile(`(?P<first>\d+)\.(\d+).(?P<second>\d+)`)

func main() {
  fmt.Printf("%+v", myExp.FindStringSubmatch("1234.5678.9"))

  match := myExp.FindStringSubmatch("1234.5678.9")
    for i, name := range myExp.SubexpNames() {
        fmt.Printf("'%s'\t %d -> %s\n", name, i, match[i])
    }
    //fmt.Printf("by name: %s %s\n", match["first"], match["second"])
}

The commented out line is how I would expect to access the named fields in Python. What's the equivalent way to do this in go?

Or if I need to convert the match to a map, what's the most idiomatic way in go to make and then access the map?

2
  • Since I can't add a comment below to the first proposed answer, that seems like an awful lot of code to just make a map. I would suggest you edit the answer to show accessing a value in the map. e.g. result := myExp.FindStringSubmatchMap("1234.5678.9") fmt.Printf("%s\n", result["second"]) Dec 23, 2013 at 22:01
  • 1
    There is no method named FindStringSubmatchMap.
    – chmike
    Jul 12, 2017 at 9:28

4 Answers 4

79

You can reference your named capture groups by utilizing map as follows:

package main

import (
    "fmt"
    "regexp"
)

var myExp = regexp.MustCompile(`(?P<first>\d+)\.(\d+).(?P<second>\d+)`)

func main() {
    match := myExp.FindStringSubmatch("1234.5678.9")
    result := make(map[string]string)
    for i, name := range myExp.SubexpNames() {
        if i != 0 && name != "" {
            result[name] = match[i]
        }
    }
    fmt.Printf("by name: %s %s\n", result["first"], result["second"])
}

GoPlay

1
  • 3
    Also want && name != "" (after i != 0) so capture groups without names don't make it into the map.
    – Max Krohn
    Aug 22, 2017 at 1:29
17

I don't have the reputation to comment so forgive me if this shouldn't be an 'answer', but I found the above answer helpful so I wrapped it in to a function:

func reSubMatchMap(r *regexp.Regexp, str string) (map[string]string) {
    match := r.FindStringSubmatch(str)
    subMatchMap := make(map[string]string)
    for i, name := range r.SubexpNames() {
        if i != 0 {
            subMatchMap[name] = match[i]
        }
    }

    return subMatchMap
}

Example usage on Playground: https://play.golang.org/p/LPLND6FnTXO

Hope this is helpful to someone else. Love the ease of named capture groups in Go.

1
  • An error will be thrown if there's no match and range r.SubexpNames() is being iterated. Iterating over the matched content will just return nil instead, like in the answer above: stackoverflow.com/a/53587770/422848. Mar 29, 2020 at 15:38
12

The other approaches will throw an error when a match wasn't found for a 'named group'.

The following, however, creates a map with whatever named groups were actually found:

func findNamedMatches(regex *regexp.Regexp, str string) map[string]string {
    match := regex.FindStringSubmatch(str)

    results := map[string]string{}
    for i, name := range match {
        results[regex.SubexpNames()[i]] = name
    }
    return results
}

This approach will just return the map with the named group matches. If there are no matches, it'll just return an empty map. I've found that's much easier to deal with than errors being thrown if a match isn't found.

3
  • "remote" must be "str" and "repoRegex" must be "regex". After that this works great, thanks!! Jul 31, 2019 at 10:26
  • Pedantically, it will not return nil if there are no matches: it will return an empty, but non-nil, map. go.dev/play/p/Gxhd0Ot4nqY Mar 25, 2022 at 22:13
  • Good point! Thanks. I've updated the answer to specify that.
    – russt
    Mar 27, 2022 at 20:55
2

You can use regroup library for that https://github.com/oriser/regroup

Example:

package main

import (
    "fmt"

    "github.com/oriser/regroup"
)

var myExp = regroup.MustCompile(`(?P<first>\d+)\.(\d+).(?P<second>\d+)`)

func main() {
    match, err := myExp.Groups("1234.5678.9")
    if err != nil {
        panic(err)
    }
    fmt.Printf("by name: %s %s\n", match["first"], match["second"])
}

Playground

You can also use a struct for that:

package main

import (
    "fmt"

    "github.com/oriser/regroup"
)

type Example struct {
    First  int `regroup:"first"`
    Second int `regroup:"second"`
}

var myExp = regroup.MustCompile(`(?P<first>\d+)\.(\d+).(?P<second>\d+)`)

func main() {
    res := &Example{}
    err := myExp.MatchToTarget("1234.5678.9", res)
    if err != nil {
        panic(err)
    }
    fmt.Printf("by struct: %+v\n", res)
}

Playground

1
  • Best one. Fit my needs perfectly. May 5, 2022 at 13:33

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.