Python 正则表达式多重搜索
我需要在一个字符串中查找多个单词。
import re
words = [{'word':'test1', 'case':False}, {'word':'test2', 'case':False}]
status = "test1 test2"
for w in words:
if w['case']:
r = re.compile("\s#?%s" % w['word'], re.IGNORECASE|re.MULTILINE)
else:
r = re.compile("\s#?%s" % w['word'], re.MULTILINE)
if r.search(status):
print "Found word %s" % w['word']
但不知为什么,这段代码只会找到“test2”,而从来找不到“test1”。这是为什么呢?
我知道可以用“|”来分隔搜索的单词,但可能会有成百上千个单词,所以我才使用循环来处理。
2 个回答
2
正如Martijn提到的,在test1
前面没有空格。而且你的代码在处理单词较长的情况时也不太对。比如,它会把test2blabla
当作test2
的一种情况,我不确定这是不是你想要的结果。
我建议使用单词边界的正则表达式\b
:
for w in words:
if w['case']:
r = re.compile(r"\b%s\b" % w['word'], re.IGNORECASE|re.MULTILINE)
else:
r = re.compile(r"\b%s\b" % w['word'], re.MULTILINE)
if r.search(status):
print "Found word %s" % w['word']
编辑:
我应该指出,如果你真的只想允许(空格)单词或(空格)#单词
这种格式,那么你就不能使用\b
。
9
在status
中,test1
前面没有空格,而你生成的正则表达式却要求前面有空格。
你可以修改测试,让它可以匹配空格后面或者行的开头:
for w in words:
if w['case']:
r = re.compile("(^|\s)#?%s" % w['word'], re.IGNORECASE|re.MULTILINE)
else:
r = re.compile("(^|\s)#?%s" % w['word'], re.MULTILINE)
if r.search(status):
print "Found word %s" % w['word']