Unverified Commit 705a827b authored by panty's avatar panty Committed by GitHub

add IsMatchPattern (#27)

* add IsMatchPattern

* add comment

* fix by code review
parent 85479285
...@@ -20,6 +20,7 @@ package gxstrings ...@@ -20,6 +20,7 @@ package gxstrings
import ( import (
"reflect" "reflect"
"regexp" "regexp"
"strings"
) )
func IsNil(i interface{}) bool { func IsNil(i interface{}) bool {
...@@ -46,3 +47,34 @@ func RegSplit(text string, regexSplit string) []string { ...@@ -46,3 +47,34 @@ func RegSplit(text string, regexSplit string) []string {
result[len(indexes)] = text[lastStart:] result[len(indexes)] = text[lastStart:]
return result return result
} }
// IsMatchPattern is used to determine whether pattern
// and value match with wildcards currently supported *
func IsMatchPattern(pattern string, value string) bool {
if "*" == pattern {
return true
}
if len(pattern) == 0 && len(value) == 0 {
return true
}
if len(pattern) == 0 || len(value) == 0 {
return false
}
i := strings.LastIndex(pattern, "*")
switch i {
case -1:
// doesn't find "*"
return value == pattern
case len(pattern) - 1:
// "*" is at the end
return strings.HasPrefix(value, pattern[0:i])
case 0:
// "*" is at the beginning
return strings.HasSuffix(value, pattern[1:])
default:
// "*" is in the middle
prefix := pattern[0:i]
suffix := pattern[i+1:]
return strings.HasPrefix(value, prefix) && strings.HasSuffix(value, suffix)
}
}
...@@ -32,3 +32,15 @@ func Test_RegSplit(t *testing.T) { ...@@ -32,3 +32,15 @@ func Test_RegSplit(t *testing.T) {
assert.Equal(t, "jsonrpc://127.0.0.1", strings[1]) assert.Equal(t, "jsonrpc://127.0.0.1", strings[1])
assert.Equal(t, "registry://3.2.1.3?registry=zookeeper", strings[2]) assert.Equal(t, "registry://3.2.1.3?registry=zookeeper", strings[2])
} }
func TestIsMatchPattern(t *testing.T) {
assert.Equal(t, true, IsMatchPattern("*", "value"))
assert.Equal(t, true, IsMatchPattern("", ""))
assert.Equal(t, false, IsMatchPattern("", "value"))
assert.Equal(t, true, IsMatchPattern("value", "value"))
assert.Equal(t, true, IsMatchPattern("v*", "value"))
assert.Equal(t, true, IsMatchPattern("*ue", "value"))
assert.Equal(t, true, IsMatchPattern("*e", "value"))
assert.Equal(t, true, IsMatchPattern("v*e", "value"))
assert.Equal(t, true, IsMatchPattern("val*e", "value"))
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment