码迷,mamicode.com
首页 > 其他好文 > 详细

字符串忽略大小写的搜索和替换

时间:2019-11-05 21:40:07      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:case   pre   api   匹配   字符串   ret   replace   code   upper   

需求:字符串忽略大小写搜索和替换

解决:
  • 使用re.IGNORECASE
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)

字符串忽略大小写的搜索和替换

标签:case   pre   api   匹配   字符串   ret   replace   code   upper   

原文地址:https://www.cnblogs.com/action-go/p/11801641.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!