Python 正则表达式多重搜索

7 投票
2 回答
6545 浏览
提问于 2025-04-16 18:31

我需要在一个字符串中查找多个单词。

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']

撰写回答