Skip to content

Commit

Permalink
✨ feat: str - add new func LikeMatch() simple match string like the S…
Browse files Browse the repository at this point in the history
…QL LIKE
  • Loading branch information
inhere committed Jun 4, 2023
1 parent ba11691 commit 0a10991
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
23 changes: 23 additions & 0 deletions strutil/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,29 @@ func GlobMatch(pattern, s string) bool {
return ok
}

// LikeMatch simple check for a string match the pattern. pattern like the SQL LIKE.
func LikeMatch(pattern, s string) bool {
ln := len(pattern)
if ln < 2 {
return false
}

// eg `%abc` `%abc%`
if pattern[0] == '%' {
if ln > 2 && pattern[ln-1] == '%' {
return strings.Contains(s, pattern[1:ln-1])
} else {
return strings.HasSuffix(s, pattern[1:])
}
}

// eg `abc%`
if pattern[ln-1] == '%' {
return strings.HasPrefix(s, pattern[:ln-1])
}
return pattern == s
}

// MatchNodePath check for a string match the pattern.
//
// Use on pattern:
Expand Down
25 changes: 25 additions & 0 deletions strutil/check_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -266,3 +266,28 @@ func TestSimpleMatch(t *testing.T) {
assert.False(t, strutil.SimpleMatch(str, []string{"hi", "^inhere"}))
assert.False(t, strutil.SimpleMatch(str, []string{"hi", "inhere$"}))
}

func TestLikeMatch(t *testing.T) {
tests := []struct {
p, s string
ok bool
}{
{"a%", "abc", true},
{"%a%", "abc", true},
{"a%", "ab.cd.ef", true},
{"%c", "abc", true},
{"%c", "cdf", false},
{"%c%", "cdf", true},
{"%cd%", "cdf", true},
{"%d%", "cdf", true},
{"%df%", "cdf", true},
{"%c", "", false},
{"abc", "abc", true},
{"abc", "def", false},
}

for _, tt := range tests {
assert.Eq(t, tt.ok, strutil.LikeMatch(tt.p, tt.s))
}

}

0 comments on commit 0a10991

Please sign in to comment.