Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex matching apart from a character set

I am trying to find all characters that are not c, i, k, m, o or v in a string. The regex pattern I am using at the moment is [abd-hjlnp-wx-z].

I was wondering if I could do something like [a-z AND not [cikmov]]. I am using python 2.7.

like image 305
stephanos Avatar asked Aug 01 '26 05:08

stephanos


1 Answers

You can use a negative character class here. Start with \W (not a word); negated that means everything that is a word character, but you can then add all your exceptions:

[^\W_0-9cikmov]

[^...] is a negative character class, everything in the class must not match. With \W that means anything that is not in the ranges a-z, A-Z, 0-9 or and underscore would match, the ^ inverted that so we now match all letters, numbers and underscores.

To that we added numbers and an underscore, so now it only matches letters again. Then add your exceptions, and it'll only match all letters except c, i, k, m, o or v. The uppercase versions are still matched, unless you make the regex case insensitive.

Demo:

>>> import re
>>> re.findall(r'[^\W_0-9cikmov]', "Don't match 1232 or cikmov")
['D', 'n', 't', 'a', 't', 'h', 'r']

All letters were matched, except for your exceptions.

like image 74
Martijn Pieters Avatar answered Aug 03 '26 05:08

Martijn Pieters