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

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

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

相关文章

正则替换html代码中img标签的src值在开发富文本信息在移动端...
正则表达式
AWK是一种处理文本文件的语言,是一个强大的文件分析工具。它...
正则表达式是特殊的字符序列,利用事先定义好的特定字符以及...
Python界一名小学生,热心分享编程学习。
收集整理每周优质开发者内容,包括、、等方面。每周五定期发...