Case insensitive regular expression without re.compile?
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)
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'
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 define case insensitive during the pattern compile:
pattern = re.compile('FIle:/+(.*)', re.IGNORECASE)
In imports
import re
In run time processing:
RE_TEST = r'test'
if re.match(RE_TEST, 'TeSt', re.IGNORECASE):
It should be mentioned that not using re.compile
is wasteful. Every time the above match method is called, the regular expression will be compiled. This is also faulty practice in other programming languages. The below is the better practice.
In app initialization:
self.RE_TEST = re.compile('test', re.IGNORECASE)
In run time processing:
if self.RE_TEST.match('TeSt'):