diff options
Diffstat (limited to 'pkg')
-rw-r--r-- | pkg/utils/regexp.go | 17 | ||||
-rw-r--r-- | pkg/utils/regexp_test.go | 44 |
2 files changed, 61 insertions, 0 deletions
diff --git a/pkg/utils/regexp.go b/pkg/utils/regexp.go new file mode 100644 index 000000000..2ceab1d71 --- /dev/null +++ b/pkg/utils/regexp.go @@ -0,0 +1,17 @@ +package utils + +import "regexp" + +func FindNamedMatches(regex *regexp.Regexp, str string) map[string]string { + match := regex.FindStringSubmatch(str) + + if len(match) == 0 { + return nil + } + + results := map[string]string{} + for i, value := range match[1:] { + results[regex.SubexpNames()[i+1]] = value + } + return results +} diff --git a/pkg/utils/regexp_test.go b/pkg/utils/regexp_test.go new file mode 100644 index 000000000..03afe7065 --- /dev/null +++ b/pkg/utils/regexp_test.go @@ -0,0 +1,44 @@ +package utils + +import ( + "reflect" + "regexp" + "testing" +) + +func TestFindNamedMatches(t *testing.T) { + scenarios := []struct { + regex *regexp.Regexp + input string + expected map[string]string + }{ + { + regexp.MustCompile(`^(?P<name>\w+)`), + "hello world", + map[string]string{ + "name": "hello", + }, + }, + { + regexp.MustCompile(`^https?://.*/(?P<owner>.*)/(?P<repo>.*?)(\.git)?$`), + "https://my_username@bitbucket.org/johndoe/social_network.git", + map[string]string{ + "owner": "johndoe", + "repo": "social_network", + "": ".git", // unnamed capture group + }, + }, + { + regexp.MustCompile(`(?P<owner>hello) world`), + "yo world", + nil, + }, + } + + for _, scenario := range scenarios { + actual := FindNamedMatches(scenario.regex, scenario.input) + if !reflect.DeepEqual(actual, scenario.expected) { + t.Errorf("FindNamedMatches(%s, %s) == %s, expected %s", scenario.regex, scenario.input, actual, scenario.expected) + } + } +} |