遇到这么一道题:正则匹配,规定“+”匹配任何一个字符,“*”匹配任何0个或多个字符,自己写一个函数实现这个功能。
def get_last_index(string, s):
if not string:
return -1
i = len(string) - 1
while i >= 0:
if string[i] == s:
return i
i -= 1
return -1
def simplify(pattern,string):
i = -1
j = -1
while i < len(pattern):
if j >= len(string):
return False
if pattern[i] == string[j]:
i += 1
j += 1
else:
if pattern[i] == "+":
i += 1
j += 1
elif pattern[i] == "*":
if i == len(pattern) - 1:
return True
else:
last_char = pattern[i+1]
last_index = get_last_index(string, last_char)
if last_index == -1:
return False
else:
i += 1
j = last_index
else:
return False
return True
l = [
["abc+zx*a", "abchzxxx"],
]
for [a,b] in l:
print (a,b, simplify(a,b))