diff --git a/strutil/check.go b/strutil/check.go index 1cb661ff8..899d03644 100644 --- a/strutil/check.go +++ b/strutil/check.go @@ -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, '*') { diff --git a/strutil/check_test.go b/strutil/check_test.go index 472e6d956..fbee96b7b 100644 --- a/strutil/check_test.go +++ b/strutil/check_test.go @@ -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"})) +} diff --git a/strutil/textutil/textutil.go b/strutil/textutil/textutil.go index 3ccd9db27..0c65d9b96 100644 --- a/strutil/textutil/textutil.go +++ b/strutil/textutil/textutil.go @@ -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.