regex to match entire words containing only certain characters

后端 未结 4 1328
無奈伤痛
無奈伤痛 2021-01-18 06:01

I want to match entire words (or strings really) that containing only defined characters.

For example if the letters are d, o, g

4条回答
  •  礼貌的吻别
    2021-01-18 06:25

    This should work for you

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

    Explanation

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

提交回复
热议问题