Python 匹配单词边界标点(包括下划线)的正则表达式

Python 匹配单词边界标点(包括下划线)的正则表达式,python,regex,Python,Regex,我正在为具有以下属性的变量短语寻找Python正则表达式: (为了举例,让我们假设变量短语在这里取值和。但是请注意,我需要这样做,扮演和角色的东西可以作为变量传入,我将其称为短语) 应匹配:此和,此和,(和),[和],和^,;和等 不应匹配:land,andy 这就是我到目前为止所尝试的(其中,短语扮演着和的角色): 这似乎适用于我的所有要求,但它与带下划线的单词不匹配,例如\\\\\\\\\\\\\\\\,hello\\\\\\\\,hello\\\\\\\\\\\ 编辑:理想情况下,我希望使

我正在为具有以下属性的变量短语寻找Python正则表达式: (为了举例,让我们假设变量短语在这里取值
。但是请注意,我需要这样做,扮演
角色的东西可以作为变量传入,我将其称为
短语

应匹配:
此和
此和
(和)
[和]
和^
;和

不应匹配:
land
andy

这就是我到目前为止所尝试的(其中,
短语
扮演着
的角色):

这似乎适用于我的所有要求,但它与带下划线的单词不匹配,例如
\\\\\\\\\\\\\\\\
hello\\\\\\\\
hello\\\\\\\\\\\


编辑:理想情况下,我希望使用标准库re模块,而不是任何外部软件包。

这里有一个正则表达式可以解决这个问题:

Regex

(?<=[\W_]+|^)and(?=[\W_]+|$)
但是,如果您坚持使用
re
,那么我建议您将lookback一分为二
(?您可以使用

r'(?<![^\W_])and(?![^\W_])'
输出:

this_and: True
this.and: True
(and): True
[and]: True
and^: True
;And: True
land: False
andy: False

谢谢。我需要扮演
角色的东西成为一个变量,我称之为
短语
(更新了问题以反映这一点)。根据你所说的,我尝试了“pattern=r”(?)@亚历山大,我知道。我还没试过,但是我怀疑这个错误实际上是因为使用了模块<代码> Re>代码>。试着使用模块<代码> ReXEX <代码>。它可能会起作用。我认为你需要一个自定义的单词边界,后面有一个否定的后视。看,你有时间检查答案吗?请考虑接受一个最有效的单词。为你。
# This works fine
# import regex
word = 'and'
pattern = r'(?<=[\W_]+|^){}(?=[\W_]+|$)'.format(word.lower())
string = 'this_And'
regex.search(pattern, string.lower())
# This also works fine
# import re
word = 'and'
pattern = r'(?<=[\W_]){}(?=[\W_]+|$)|^{}(?=[\W_]+|$)'.format(word.lower(), word.lower())
string = 'this_And'
re.search(pattern, string.lower())
r'(?<![^\W_])and(?![^\W_])'
import re
strs = ['this_and', 'this.and', '(and)', '[and]', 'and^', ';And', 'land', 'andy']
phrase = "and"
rx = re.compile(r'(?<![^\W_]){}(?![^\W_])'.format(re.escape(phrase)), re.I)
for s in strs:
    print("{}: {}".format(s, bool(rx.search(s))))
this_and: True
this.and: True
(and): True
[and]: True
and^: True
;And: True
land: False
andy: False