微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

正则表达式匹配仅包含特定字符的整个单词

我想匹配仅包含已定义字符的整个单词(或字符串).

例如,如果字母是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 “,”
)
"""

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐