Case insensitive regular expression without re.compile?
The case-insensitive marker, (?i)
can be incorporated directly into the regex pattern:
>>> import re
>>> s = 'This is one Test, another TEST, and another test.'
>>> re.findall('(?i)test', s)
['Test', 'TEST', 'test']
You can also perform case insensitive searches using search/match without the IGNORECASE flag (tested in Python 2.7.3):
re.search(r'(?i)test', 'TeSt').group() ## returns 'TeSt'
re.match(r'(?i)test', 'TeSt').group() ## returns 'TeSt'
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)