You may use lookarounds:
(?:|(?<=_))word(?=|_)
^^^^^^^^^^^^^ ^^^^^^^
See the regex demo where (?:|(?<=_))
is a non-capturing group matching either a word boundary or a location preceded with _
, and (?=|_)
is a positive lookahead matching either a word boundary or a _
symbol.
Unfortunately, Python re
won't allow using (?<=|_)
as the lookbehind pattern should be of fixed width (else, you will get look-behind requires fixed-width pattern
error).
A Python demo:
import re
rx = r"(?:|(?<=_))word(?=|_)"
s = "some_word_here and a word there"
print(re.findall(rx,s))
An alternative solution is to use custom word boundaries like (?<![^W_])
/ (?![^W_])
(see online demo):
rx = r"(?<![^W_])word(?![^W_])"
The (?<![^W_])
negative lookbehind fails a match if there is no character other than non-word and _
char (so, it requires the start of string or any word char excluding _
before the search word) and (?![^W_])
negative lookahead will fail the match if there is no char other than non-word and _
char (that is, requires the end of string or a word char excluding _
).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…