Regular expressions match exact word

杀马特。学长 韩版系。学妹 提交于 2021-02-05 09:35:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!