Python实现字符串模糊匹配
在一个字符串中,有时需对其中某些内容进行模糊匹配以实现条件的判定,如在“你好,hello,world”中判断是否含有“llo”。Python中通过re.search()方法实现,特别地,对于首位起始的内容匹配,也可通过re.match()方法实现。若匹配成功,它们返回一个re.Match对象;若匹配失败,返回None。
re.search()实现模糊匹配
import re
teststr = "你好,hello,world"
print('\n',teststr,'\n')
pattern1 = "llo"
r1 = re.search(pattern1, teststr)
if r1:
print(pattern1,'匹配成功.')
else:
print(pattern1,'匹配失败.')
pattern2 = "你好"
r2 = re.search(pattern2, teststr)
if r2:
print(pattern2,"匹配成功.")
else:
print(pattern2,"匹配失败.")
re.match()实现首位起始的模糊匹配
teststr = "你好,hello,world"
print('\n',teststr,'\n')
pattern1 = "llo"
r1 = re.match(pattern1, teststr)
if r1:
print(pattern1,'匹配成功.')
else:
print(pattern1,'匹配失败.')
pattern2 = "你好"
r2 = re.match(pattern2, teststr)
if r2:
print(pattern2,"匹配成功.")
else:
print(pattern2,"匹配失败.")
End.