parent
29649167ab
commit
b3b965ba0a
@ -0,0 +1,35 @@
|
|||||||
|
package regx
|
||||||
|
|
||||||
|
func isCharMatch(text, pattern string) bool {
|
||||||
|
return pattern[0] == '.' || pattern[0] == text[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
func matchStar(text, pattern string) bool {
|
||||||
|
for {
|
||||||
|
switch {
|
||||||
|
case isMatch(text, pattern[2:]):
|
||||||
|
return true
|
||||||
|
case text == "" || !isCharMatch(text, pattern):
|
||||||
|
return false
|
||||||
|
default:
|
||||||
|
text = text[1:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func isMatch(text, pattern string) bool {
|
||||||
|
switch {
|
||||||
|
case pattern == "":
|
||||||
|
return text == ""
|
||||||
|
case len(pattern) >= 2 && pattern[1] == '*':
|
||||||
|
return matchStar(text, pattern)
|
||||||
|
case text != "" && isCharMatch(text, pattern):
|
||||||
|
return isMatch(text[1:], pattern[1:])
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsMatch(text, pattern string) bool {
|
||||||
|
return isMatch(text, pattern)
|
||||||
|
}
|
@ -0,0 +1,52 @@
|
|||||||
|
package regx_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.jxs.me/leetgo/regx"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestEmpty(t *testing.T) {
|
||||||
|
require.True(t, regx.IsMatch("", ""))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSingleMatch(t *testing.T) {
|
||||||
|
require.True(t, regx.IsMatch("a", "a"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSingleNonMatch(t *testing.T) {
|
||||||
|
require.False(t, regx.IsMatch("b", "a"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMultiMatch(t *testing.T) {
|
||||||
|
require.True(t, regx.IsMatch("aba", "aba"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMultiNonMatch(t *testing.T) {
|
||||||
|
require.False(t, regx.IsMatch("abca", "abac"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWildMatch(t *testing.T) {
|
||||||
|
require.True(t, regx.IsMatch("hello", "h.ll."))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWildNonMatch(t *testing.T) {
|
||||||
|
require.False(t, regx.IsMatch("hello", "hall."))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManyMatch(t *testing.T) {
|
||||||
|
require.True(t, regx.IsMatch("greeet", "gre*t"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManyMisMatch(t *testing.T) {
|
||||||
|
require.True(t, regx.IsMatch("greet", "gre*a*t"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWildcardManyMatch(t *testing.T) {
|
||||||
|
require.True(t, regx.IsMatch("anything", ".*"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWildcardNonGreedyMatch(t *testing.T) {
|
||||||
|
require.True(t, regx.IsMatch("bbba", ".*a"))
|
||||||
|
}
|
Loading…
Reference in new issue