我正在尝试找到一种方法来匹配 python 中字符串 s 中的模式 p。
s = 'abccba'
ss = 'facebookgooglemsmsgooglefacebook'
p = 'xyzzyx'
# s, p -> a, z # s and p can only be 'a' through 'z'
def match(s, p):
if s matches p:
return True
else:
return False
match(s, p) # return True
match(ss, p) # return True
我刚试过:
import re
s = "abccba"
f = "facebookgooglemsmsgooglefacebook"
p = "xyzzyx"
def fmatch(s, p):
p = re.compile(p)
m = p.match(s)
if m:
return True
else:
return False
print fmatch(s, p)
print fmatch(f, p)
两者都返回false;它们应该是真实的。
最佳答案
我将您的模式转换为正则表达式,然后可由 re.match
使用。例如,您的 xyzzyx
变为 (.+)(.+)(.+)\3\2\1$
(每个字母的第一次出现成为捕获组(.+)
,随后出现的将成为正确的反向引用)。
import re
s = 'abccba'
ss = 'facebookgooglemsmsgooglefacebook'
p = 'xyzzyx'
def match(s, p):
nr = {}
regex = []
for c in p:
if c not in nr:
regex.append('(.+)')
nr[c] = len(nr) + 1
else:
regex.append('\\%d' % nr[c])
return bool(re.match(''.join(regex) + '$', s))
print(match(s, p))
print(match(ss, p))
关于Python:在字符串中查找模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30358266/