Replace case ignored for string search
problem
You need to search and replace text strings in a way that ignores case .
solution
In order to ignore case in text operations , You need to use re The module provides these operations with re.IGNORECASE Flag parameter . such as :
>>> text = 'UPPER PYTHON, lower python, Mixed Python'
>>> re.findall('python', text, flags=re.IGNORECASE)
['PYTHON', 'python', 'Python']
>>> re.sub('python', 'snake', text, flags=re.IGNORECASE)
'UPPER snake, lower snake, Mixed snake'
>>>
The last example reveals a small flaw , The replacement string does not automatically match the case of the matched string . To fix this , You may need an auxiliary function , Like the following :
def matchcase(word):
def replace(m):
text = m.group()
if text.isupper():
return word.upper()
elif text.islower():
return word.lower()
elif text[0].isupper():
return word.capitalize()
else:
return word
return replace
Here's how to use the above function :
>>> re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE)
'UPPER SNAKE, lower snake, Mixed Snake'
>>>
Discuss
For general matching operations that ignore case , Simply pass on one re.IGNORECASE The flag parameter is enough .