1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

feat: add RegexMatchAllGroups

This commit is contained in:
dudaodong
2024-09-06 14:19:57 +08:00
parent 93be25920f
commit 90e5a0bfb2
5 changed files with 138 additions and 2 deletions

View File

@@ -727,3 +727,11 @@ func TemplateReplace(template string, data map[string]string) string {
return result
}
// RegexMatchAllGroups Matches all subgroups in a string using a regular expression and returns the result.
// Play: todo
func RegexMatchAllGroups(pattern, str string) [][]string {
re := regexp.MustCompile(pattern)
matches := re.FindAllStringSubmatch(str, -1)
return matches
}

View File

@@ -739,3 +739,17 @@ func ExampleTemplateReplace() {
// Output:
// Hello, my name is Bob, I'm 20 years old.
}
func ExampleRegexMatchAllGroups() {
pattern := `(\w+\.+\w+)@(\w+)\.(\w+)`
str := "Emails: john.doe@example.com and jane.doe@example.com"
result := RegexMatchAllGroups(pattern, str)
fmt.Println(result[0])
fmt.Println(result[1])
// Output:
// [john.doe@example.com john.doe example com]
// [jane.doe@example.com jane.doe example com]
}

View File

@@ -810,3 +810,46 @@ func TestTemplateReplace(t *testing.T) {
assert.Equal(expected, result)
})
}
func TestRegexMatchAllGroups(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestRegexMatchAllGroups")
tests := []struct {
pattern string
str string
expected [][]string
}{
{
pattern: `(\w+\.+\w+)@(\w+)\.(\w+)`,
str: "Emails: john.doe@example.com and jane.doe@example.com",
expected: [][]string{{"john.doe@example.com", "john.doe", "example", "com"}, {"jane.doe@example.com", "jane.doe", "example", "com"}},
},
{
pattern: `(\d+)`,
str: "No numbers here!",
expected: nil,
},
{
pattern: `(\d{3})-(\d{2})-(\d{4})`,
str: "My number is 123-45-6789",
expected: [][]string{{"123-45-6789", "123", "45", "6789"}},
},
{
pattern: `(\w+)\s(\d+)`,
str: "Item A 123, Item B 456",
expected: [][]string{{"A 123", "A", "123"}, {"B 456", "B", "456"}},
},
{
pattern: `(\d{2})-(\d{2})-(\d{4})`,
str: "Dates: 01-01-2020, 12-31-1999",
expected: [][]string{{"01-01-2020", "01", "01", "2020"}, {"12-31-1999", "12", "31", "1999"}},
},
}
for _, tt := range tests {
result := RegexMatchAllGroups(tt.pattern, tt.str)
assert.Equal(tt.expected, result)
}
}