python - 使用动态正则表达式匹配字符串中的整个单词

标签 python regex

我正在使用正则表达式查看某个单词是否出现在句子中。单词由空格分隔,但两边可以有标点符号。如果单词在字符串的中间,则以下匹配有效(它防止部分单词匹配,允许单词两边的标点符号)。

match_middle_words = " [^a-zA-Z\d ]{0,}" + word + "[^a-zA-Z\d ]{0,} "

然而,这不会匹配第一个或最后一个单词,因为没有尾随/前导空格。因此,对于这些情况,我也一直在使用:

match_starting_word = "^[^a-zA-Z\d]{0,}" + word + "[^a-zA-Z\d ]{0,} "
match_end_word = " [^a-zA-Z\d ]{0,}" + word + "[^a-zA-Z\d]{0,}$"

然后结合

 match_string = match_middle_words  + "|" + match_starting_word  +"|" + match_end_word 

有没有一种简单的方法可以避免需要三个匹配项。具体来说,是否有一种方法可以指定'ether 一个空格或文件开头(即“^”)和类似的'一个空格或文件结尾(即“$”)?

最佳答案

为什么不使用单词边界

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 个备选方案是没有用的。

Sample code :

import re
strn = "word hereword word, there word"
search = "word"
print re.findall(r"\b" + search + r"\b", strn)

我们找到了 3 个匹配项:

['word', 'word', 'word']

注意“单词”边界

当“单词”实际上是任何字符的 block 时,您应该 re.escape在传递给正则表达式模式之前:

match_string = r'\b{}\b'.format(re.escape(word)) # a single escaped "word" string passed
match_string = r'\b(?:{})\b'.format("|".join(map(re.escape, words))) # words list is escaped
match_string = rf'\b(?:{"|".join(map(re.escape, words))})\b' # Same as above for Python 3.7+

如果要匹配的单词可能以特殊字符开头/结尾,\b won't work ,使用明确的单词边界:

match_string = r'(?<!\w){}(?!\w)'.format(re.escape(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))) 

关于python - 使用动态正则表达式匹配字符串中的整个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29996079/

相关文章:

python - 在 css 文件中查找类并用 python 将它们写入新文件中

python - 遍历 Python 中的字符串元素列表,并将该迭代器变成一个 int

javascript - 正则表达式:在一个字符串中多次检查javascript

python - 如何连接从api下载的json文件?

python - 如何将附加参数传递给 handle_client 协程?

ruby - 使用正则表达式检查字符串是否以辅音开头

javascript - 如何在 RegExp javascript 中添加 [](方括号)?

ruby-on-rails - 如何替换字符串并保留大写?

python - 基于动态值更新 Matplotlib 中的轴

regex - 如何将字符串中的确切单词与正则表达式匹配?