【python cookbook】【字符串与文本】6.以不区分大小写的方式对文本做查找和替换

问题:以不区分大小写的方式对文本做查找和替换

解决方法:使用re模块,并对各种操作都添加上re.IGNORECASE标记

text='UPPER PYTHON,lower python,Mixed Python'

print (re.findall('python',text,re.IGNORECASE))
print (re.sub('python','snake',text,flags=re.IGNORECASE))
>>> ================================ RESTART ================================
>>> 
['PYTHON', 'python', 'Python']
UPPER snake,lower snake,Mixed snake
>>> 

以上待替换的文本与匹配的文本大小写并不吻合,例如Python替换为snake,而非Snake。若要修正该问题,需使用一个支撑函数:

import re

text='UPPER PYTHON,lower python,Mixed Python'

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()
        #capitalize()将字符串的第一个字母变成大写,其他字母变小写。
        else:
            return word
    return replace

print (re.sub('python',matchcase('snake'),text,flags=re.IGNORECASE))
>>> ================================ RESTART ================================
>>> 
UPPER SNAKE,lower snake,Mixed Snake
>>> 

 

posted @ 2016-08-20 17:21  垄上行  阅读(459)  评论(0编辑  收藏  举报