为什么不使用 单词边界 ?
match_string = r'b' + word + r'b'match_string = r'b{}b'.format(word)match_string = rf'b{word}b' # Python 3.7+ required如果您有一个单词列表(例如,在
words变量中)要与整个单词匹配,请使用
match_string = r'b(?:{})b'.format('|'.join(words))match_string = rf'b(?:{"|".join(words)})b' # Python 3.7+ required在这种情况下,您将确保仅当单词被非单词字符包围时才被捕获。另请注意,
b字符串开头和结尾处的匹配项。因此,添加3个替代方案毫无用处。
样例代码:
import restrn = "word hereword word, there word"search = "word"print re.findall(r"b" + search + r"b", strn)
我们找到了3个匹配项:
['word', 'word', 'word']
关于“单词”边界的注释
当“单词”实际上是任何字符的大块时,
re.escape在传递到正则表达式模式之前,应先将它们打包:
match_string = r'b{}b'.format(re.escape(word)) # a single escaped "word" string passedmatch_string = r'b(?:{})b'.format("|".join(map(re.escape, words))) # words list is escapedmatch_string = rf'b(?:{"|".join(map(re.escape, words))})b' # Same as above for Python 3.7+如果要匹配的单词整个单词可能以特殊字符开头/结尾,
b
将不起作用,请使用 明确的单词边界 :
match_string = r'(?<!w){}(?!w)'.format(word)match_string = r'(?<!w)(?:{})(?!w)'.format("|".join(map(re.escape, words)))如果单词边界是空格字符或字符串的开始/结尾,请使用 空格边界 ,
(?<!S)...(?!S):
match_string = r'(?<!S){}(?!S)'.format(word)match_string = r'(?<!S)(?:{})(?!S)'.format("|".join(map(re.escape, words)))


