python re.findall()不区分大小写对文本进行查找和替换

2.6 我们需要不区分大小写再文本中进行查找,或者进行替换
>>> 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'
  • 但是上述方法只能简单替换,无法保持原待替换字符的大小写状态
  • 若要做到保持原状态,需要辅助函数
  • >>> def match(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
    
  • 做如下操作替换
  • >>> re.findall('python',text,flags=re.IGNORECASE)