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
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'