unset a flag from within a python regex

Question:

I have a large collection of regular expressions, and I apply them all using a few flags with something like:

re.search(aRegex,aString,flags=re.IGNORECASE | re.UNICODE)

unfortunately, there are one or two for which I don’t want to ignore case. Python provides a handy way to set flags from within a regular expression (eg: r'(?iu)...' sets the re.IGNORECASE and re.UNICODE flags).

Is there a way that I can unset flags from within an expression? Perhaps somerthing like:

r'(?i-)...'

or

r'(?I)...'

to force case sensitivity. (btw: neither of those work..)

Asked By: drevicko

||

Answers:

There is no way to unset a flag once you set it (in the regex or in a function) in the Python 2.x re module. (There is also no way to set a flag for a portion of the regex either).

Consider using regex package if you need such feature.

Answered By: nhahtdh

As of Python 3.6 you can use (?-i:YOUR_REGEX_HERE) to unset the i (ignore case) flag for part of a regular expression (see docs).

Answered By: Trey Hunner
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.