字符串忽略大小写的搜索替换
一、 解决问题
忽略大小写的方式搜索与替换文本字符串
二、解决方案
re.IGNORECASE
三、代码说明
#!/usr/bin/env python
import re
text = 'UPPER PYTHON, lower python, Mixed Python'
resval = re.findall('python', text, flags=re.IGNORECASE)
print(resval) #['PYTHON', 'python', 'Python']
resval = re.sub('python', 'snake', text, flags=re.IGNORECASE)
print(resval) #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
resval = re.sub("python", matchcase('snake'), text, flags=re.IGNORECASE)
print(resval) #->UPPER SNAKE, lower snake, Mixed Snake
四、关联知识
re 模块传说门,待补充
五、总结
六、代码地址
github地址:https://github.com/weichen666/python_cookbook
目录/文件:first_selection/learn_str_case.py