I am looking for a Python regex for a variable phrase with the following properties:
(For the sake of example, let's assume the variable phrase here is taking the value and
. But note that I need to do this in a way that the thing playing the role of and
can be passed in as a variable which I'll call phrase
.)
Should match: this_and
, this.and
, (and)
, [and]
, and^
, ;And
, etc.
Should not match: land
, andy
This is what I tried so far (where phrase
is playing the role of and
):
pattern = r" " + re.escape(phrase.lower()) + r""
This seems to work for all my requirements except that it does not match words with underscores e.g. \_hello
, hello\_
, hello_world
.
Edit: Ideally I would like to use the standard library re module rather than any external packages.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…