This commit is contained in:
2023-03-31 13:33:06 +02:00
parent ca24e1d5bf
commit 2550691e2e
14 changed files with 331 additions and 191 deletions

View File

@@ -117,7 +117,7 @@ func (m RegexMatch) GroupByName(name string) RegexMatchGroup {
// GroupByName returns the value of a matched group (returns empty OptRegexMatchGroup if not found)
func (m RegexMatch) GroupByNameOrEmpty(name string) OptRegexMatchGroup {
for idx, subname := range m.subnames {
if subname == name {
if subname == name && (m.submatchesIndex[idx*2] != -1 || m.submatchesIndex[idx*2+1] != -1) {
return OptRegexMatchGroup{&RegexMatchGroup{haystack: m.haystack, start: m.submatchesIndex[idx*2], end: m.submatchesIndex[idx*2+1]}}
}
}

47
rext/wrapper_test.go Normal file
View File

@@ -0,0 +1,47 @@
package rext
import (
"gogs.mikescher.com/BlackForestBytes/goext/tst"
"regexp"
"testing"
)
func TestGroupByNameOrEmpty1(t *testing.T) {
regex1 := W(regexp.MustCompile("0(?P<group1>A+)B(?P<group2>C+)0"))
match1, ok1 := regex1.MatchFirst("Hello 0AAAABCCC0 Bye.")
tst.AssertTrue(t, ok1)
tst.AssertFalse(t, match1.GroupByNameOrEmpty("group1").IsEmpty())
tst.AssertEqual(t, match1.GroupByNameOrEmpty("group1").ValueOrEmpty(), "AAAA")
tst.AssertEqual(t, *match1.GroupByNameOrEmpty("group1").ValueOrNil(), "AAAA")
tst.AssertFalse(t, match1.GroupByNameOrEmpty("group2").IsEmpty())
tst.AssertEqual(t, match1.GroupByNameOrEmpty("group2").ValueOrEmpty(), "CCC")
tst.AssertEqual(t, *match1.GroupByNameOrEmpty("group2").ValueOrNil(), "CCC")
}
func TestGroupByNameOrEmpty2(t *testing.T) {
regex1 := W(regexp.MustCompile("0(?P<group1>A+)B(?P<group2>C+)(?P<group3>C+)?0"))
match1, ok1 := regex1.MatchFirst("Hello 0AAAABCCC0 Bye.")
tst.AssertTrue(t, ok1)
tst.AssertFalse(t, match1.GroupByNameOrEmpty("group1").IsEmpty())
tst.AssertEqual(t, match1.GroupByNameOrEmpty("group1").ValueOrEmpty(), "AAAA")
tst.AssertEqual(t, *match1.GroupByNameOrEmpty("group1").ValueOrNil(), "AAAA")
tst.AssertFalse(t, match1.GroupByNameOrEmpty("group2").IsEmpty())
tst.AssertEqual(t, match1.GroupByNameOrEmpty("group2").ValueOrEmpty(), "CCC")
tst.AssertEqual(t, *match1.GroupByNameOrEmpty("group2").ValueOrNil(), "CCC")
tst.AssertTrue(t, match1.GroupByNameOrEmpty("group3").IsEmpty())
tst.AssertEqual(t, match1.GroupByNameOrEmpty("group3").ValueOrEmpty(), "")
tst.AssertPtrEqual(t, match1.GroupByNameOrEmpty("group3").ValueOrNil(), nil)
}