Skip to content

Commit

Permalink
✨ feat(str): add new func SimpleMatch() for match string
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Apr 25, 2023
1 parent 2d9914c commit edc7773
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 19 deletions.
25 changes: 25 additions & 0 deletions strutil/check.go
Expand Up @@ -202,6 +202,31 @@ func VersionCompare(v1, v2, op string) bool {
}
}

// SimpleMatch all sub-string in the give text string.
//
// Difference the ContainsAll, start with ^ for exclude contains check.
func SimpleMatch(s string, keywords []string) bool {
for _, keyword := range keywords {
if keyword == "" {
continue
}

// exclude
if keyword[0] == '^' && len(keyword) > 1 {
if strings.Contains(s, keyword[1:]) {
return false
}
continue
}

// include
if !strings.Contains(s, keyword) {
return false
}
}
return true
}

// QuickMatch check for a string. pattern can be a sub string.
func QuickMatch(pattern, s string) bool {
if strings.ContainsRune(pattern, '*') {
Expand Down
6 changes: 6 additions & 0 deletions strutil/check_test.go
Expand Up @@ -246,3 +246,9 @@ func TestHasEmpty(t *testing.T) {
assert.False(t, strutil.IsAllEmpty("ab", "", "ef"))
assert.True(t, strutil.IsAllEmpty("", ""))
}

func TestSimpleMatch(t *testing.T) {
str := "hi inhere, age is 120"
assert.True(t, strutil.SimpleMatch(str, []string{"hi", "inhere"}))
assert.False(t, strutil.SimpleMatch(str, []string{"hi", "^inhere"}))
}
20 changes: 1 addition & 19 deletions strutil/textutil/textutil.go
Expand Up @@ -28,25 +28,7 @@ func RenderSMap(text string, vars map[string]string, format string) string {
//
// TIP: can use ^ for exclude match.
func IsMatchAll(s string, keywords []string) bool {
for _, keyword := range keywords {
if keyword == "" {
continue
}

// exclude
if keyword[0] == '^' && len(keyword) > 1 {
if strings.Contains(s, keyword[1:]) {
return false
}
continue
}

// include
if !strings.Contains(s, keyword) {
return false
}
}
return true
return strutil.SimpleMatch(s, keywords)
}

// ParseInlineINI parse config string to string-map. it's like INI format contents.
Expand Down

0 comments on commit edc7773

Please sign in to comment.