Python實用技法第25篇:正則:以不區分大小寫的方式對文本做查找和替換

1、需求

我們需要以不區分大小寫的方式在文本中進行查找,可能還需要做替換。

2、解決方案

要進行不區分大小寫的文本操作,我們需要使用re模塊並且對各種操作都要加上re.IGNORECASE標記。

示例:

import re
text='Mark is a handsome guy and mark is only 18 years old.'
result1=re.findall('mark',text,flags=re.IGNORECASE)
result2=re.sub('mark','python',text,flags=re.IGNORECASE)

print(result1)
print(result2)
Python資源分享qun 784758214 ,內有安裝包,PDF,學習視頻,這裏是Python學習者的聚集地,零基礎,進階,都歡迎

結果:

['Mark', 'mark']
python is a handsome guy and python is only 18 years old.

上面例子揭示了一種侷限,就是雖然名字從【mark】替換爲【python】,但是大小寫並不吻合,例如第一個人名替換後應該也是大寫:【Pyhton】。

如果想要修正這個問題,需要用到一個支撐函數,實例如下:

import re
text='Mark is a handsome guy and mark is only 18 years old.MARK'

def matchcase(word):
    def replace(m):
        #re.sub會將匹配到的對象,循環調用replace方法傳入
        print(m)
        #獲取匹配的文本
        text=m.group()
        if text.isupper():
            #如果文本全部是大寫,就返回word的全部大寫模式
            return word.upper()
        elif text.islower():
            # 如果文本全部是小寫,就返回word的全部小寫模式
            return word.lower()
        elif text[0].isupper():
            #如果文本是首字母大寫,就返回word的首字母大寫模式
            return word.capitalize()
        else:
            #其他情況,直接返回word
            return word
    return replace

result=re.sub('mark',matchcase('python'),text,flags=re.IGNORECASE)

print(result)

運行結果:

<re.Match object; span=(0, 4), match='Mark'>
<re.Match object; span=(27, 31), match='mark'>
<re.Match object; span=(53, 57), match='MARK'>
Python is a handsome guy and python is only 18 years old.PYTHON
Python資源分享qun 784758214 ,內有安裝包,PDF,學習視頻,這裏是Python學習者的聚集地,零基礎,進階,都歡迎

3、分析

對於簡單的情況,只需加上re.IGNORECASE標記足以進行不區分大小寫的匹配操作了。

但請注意,對於某些涉及大寫轉換的Unicode匹配來說可能是不夠的,以後章節會講到。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章