Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive regular expression without re.compile?

In Python, I can compile a regular expression to be case-insensitive using re.compile:

>>> s = 'TeSt' >>> casesensitive = re.compile('test') >>> ignorecase = re.compile('test', re.IGNORECASE) >>>  >>> print casesensitive.match(s) None >>> print ignorecase.match(s) <_sre.SRE_Match object at 0x02F0B608> 

Is there a way to do the same, but without using re.compile. I can't find anything like Perl's i suffix (e.g. m/test/i) in the documentation.

like image 464
Mat Avatar asked Feb 01 '09 13:02

Mat


People also ask

Why do we need re compile?

The re. compile() method We can combine a regular expression pattern into pattern objects, which can be used for pattern matching. It also helps to search a pattern again without rewriting it.


1 Answers

Pass re.IGNORECASE to the flags param of search, match, or sub:

re.search('test', 'TeSt', re.IGNORECASE) re.match('test', 'TeSt', re.IGNORECASE) re.sub('test', 'xxxx', 'Testing', flags=re.IGNORECASE) 
like image 109
Michael Haren Avatar answered Oct 05 '22 18:10

Michael Haren