Can I mix character classes in Python RegEx?

后端 未结 4 417
长情又很酷
长情又很酷 2021-01-12 19:04

Special sequences (character classes) in Python RegEx are escapes like \\w or \\d that matches a set of characters.

In my case, I need to b

4条回答
  •  时光取名叫无心
    2021-01-12 19:15

    You can exclude classes using a negative lookahead assertion, such as r'(?!\d)[\w]' to match a word character, excluding digits. For example:

    >>> re.search(r'(?!\d)[\w]', '12bac')
    <_sre.SRE_Match object at 0xb7779218>
    >>> _.group(0)
    'b'
    

    To exclude more than one group, you can use the usual [...] syntax in the lookahead assertion, for example r'(?![0-5])[\w]' would match any alphanumeric character except for digits 0-5.

    As with [...], the above construct matches a single character. To match multiple characters, add a repetition operator:

    >>> re.search(r'((?!\d)[\w])+', '12bac15')
    <_sre.SRE_Match object at 0x7f44cd2588a0>
    >>> _.group(0)
    'bac'
    

提交回复
热议问题