Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Python regex ignore case inside a part of a pattern but not the entire expression? [duplicate]

Say I have a string containing foobar fooBAR FOObar FOOBAR, and I want to search all instances containing a case insensitive "foo" or "FOO" but a lowercase "bar". In this case, re.findall should return ['foobar', 'FOObar'].

The accepted answer for this question explains that it can be done in C# with (?i)foo(?-i)bar, but Python raises an invalid expression error.

Does the Python regex library support such a feature?

like image 238
Vortico Avatar asked Jun 05 '11 21:06

Vortico


2 Answers

Python does not support disabling flags in the same manner; you will have to handle it differently.

>>> re.match('[Ff][Oo]{2}bar', 'Foobar')
<_sre.SRE_Match object at 0x7eff94dac920>
like image 116
Ignacio Vazquez-Abrams Avatar answered Nov 20 '22 20:11

Ignacio Vazquez-Abrams


The re module doesn't support scoped flags, but there's an alternative regex implementation which does:

http://pypi.python.org/pypi/regex

like image 26
MRAB Avatar answered Nov 20 '22 19:11

MRAB