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

前端之家收集整理的这篇文章主要介绍了正则表达式匹配仅包含特定字符的整个单词前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想匹配仅包含已定义字符的整个单词(或字符串).

例如,如果字母是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@H_301_14@ 
 

在这句话中:

dog god ogd,dogs o@H_301_14@ 
 

…我期望在狗,上帝和o上匹配(不是ogd,因为s的逗号或狗)

解决方法

这应该适合你

\b[dog]+\b(?![,])@H_301_14@ 
 

说明

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 “,”
)
"""@H_301_14@

猜你在找的正则表达式相关文章