问题
I am looking to build a regular expression that matches only the occurrences of the text passed. I tried using the \b which indeed worked for a word boundary but it didn't work with symbols like ! .
>>> list(re.finditer(r'\bhe\b','he is hey!'))
[<re.Match object; span=(0, 2), match='he'>]
>>> list(re.finditer(r'\bhe\b','he is he!'))
[<re.Match object; span=(0, 2), match='he'>, <re.Match object; span=(6, 8), match='he'>]
I don't want my regular expression to match the 'he!'
回答1:
You might match a word boundary \b follwed by he and use a negative lookahead (?! to verify that what follows is not a non whitespace character \S
\bhe(?!\S)
Regex demo
Python test
来源:https://stackoverflow.com/questions/52235073/regular-expressions-match-exact-word