需求:字符串忽略大小写搜索和替换
解决:
import re
text = 'UPPER PYTHON, lower python, Mixed Python'
f = re.findall("python", text, flags=re.IGNORECASE)
print(f)
s, n = re.subn("python","snake",text, flags=re.IGNORECASE)
print(s)
print(n) # 返回匹配的次数
缺陷
替换之后的字符串与被替换的大小写不能保持一致
解决:
def matchcase(word):
def replace(m): # 匹配的结果 如:PYTHON
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
if __name__ == '__main__':
s = re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE)
print(s)