我想匹配仅包含已定义字符的整个单词(或字符串).
例如,如果字母是d,o,g:
dog = match god = match ogd = match dogs = no match (because the string also has an "s" which is not defined) gods = no match doog = match gd = match
在这句话中:
dog god ogd,dogs o
…我期望在狗,上帝和o上匹配(不是ogd,因为s的逗号或狗)
解决方法
这应该适合你
\b[dog]+\b(?![,])
说明
r""" \b # Assert position at a word boundary [dog] # Match a single character present in the list “dog” + # Between one and unlimited times,as many times as possible,giving back as needed (greedy) \b # Assert position at a word boundary (?! # Assert that it is impossible to match the regex below starting at this position (negative lookahead) [,] # Match the character “,” ) """