Python: re.IGNORECASE 标志参数字符串忽略大小写的搜索替换

为了在文本操作时忽略大小写,需要在使用re 模块的时候给这些操作提供re.IGNORECASE 标志参数。比如


>>> 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 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

下面是使用上述函数的方法:
>>> re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE)
'UPPER SNAKE, lower snake, Mixed Snake'
>>>


注: matchcase('snake') 返回了一个回调函数(参数必须是match 对象), sub() 函数除了接受替换字符串外,还能接受一个回调函数。

原文地址:https://www.cnblogs.com/baxianhua/p/8515680.html