python 正則表達式還記得嗎?來複習下吧

python 正則表達式還記得嗎?來複習下吧

編程鍵盤

貪婪模式與非貪婪模式

正則表達式通常用於查找匹配的字符串.在Python中,數量詞默認是貪婪的(在少數語言裡,也可能是非貪婪的),總是嘗試匹配儘可能多的字符;非貪婪模式正好相反,總是嘗試匹配儘可能少的字符.

python 正則表達式還記得嗎?來複習下吧

添加?可實現非貪婪模式

python 正則表達式還記得嗎?來複習下吧

結果

re.sub方法實現替換字符

re.sub(pattern,repl,string,count=0)

  • pattern : 正則中的模式字符串。
  • repl : 替換的字符串,也可為一個函數。
  • string : 要被查找替換的原始字符串。
  • count : 模式匹配後替換的最大次數,默認 0 表示替換所有的匹配。

repl(replace)參數也可以是一個函數:

import re 
# 將匹配的數字乘於 2
def double(matched):
value = int(matched.group('value'))
return str(value * 2)
s = 'A23G4HFD567'
print(re.sub('(?P<value>\\d+)', double, s))
/<value>
python 正則表達式還記得嗎?來複習下吧

repl函數

上邊的函數調用,函數名後邊都沒有括號.

下邊是幾個匹配的比較

import re
#匹配目標
def target_match(content):
result=re.match('^Hello\\s(\\d+)\\sWorld',content)
return result,result.group(),result.group(1),result.span()
#通用匹配
def gena_match(content):
result=re.match('^Hello.*Demo$',content)
return result,result.group(),result.span()
#貪婪匹配
def greed_match(content):
result=re.match('^He.*(\\d+).*Demo$',content)
return result,result.group(1)
#非貪婪匹配
def un_greed_match(content):
result=re.match('^He.*?(\\d+).*Demo$',content)
return result,result.group(1)
if __name__=='__main__':
con_match='Hello 1234567 World_This is a Regex Demo'
print(target_match(con_match))
print(gena_match(con_match))
print(greed_match(con_match))
print(un_greed_match(con_match))
結果為:
python 正則表達式還記得嗎?來複習下吧

結果


python 正則表達式還記得嗎?來複習下吧

使用了compile將正則表達式轉為了模式對象

對於上面我們也可以這樣實現:

python 正則表達式還記得嗎?來複習下吧

re.sub

使用re.compile()創建了模式對象,就必須在sub()方法中省略掉pattern這一參數項.

簡單介紹下compile()函數:

re.compile(pattern[, flags])

參數:

  • pattern : 一個字符串形式的正則表達式
  • flags 可選,表示匹配模式,比如忽略大小寫,多行模式等,具體參數為:
  • re.I 忽略大小寫
  • re.L 表示特殊字符集 \\w, \\W, \\b, \\B, \\s, \\S 依賴於當前環境
  • re.M 多行模式
  • re.S 即為' . '並且包括換行符在內的任意字符(' . '不包括換行符)
  • re.U 表示特殊字符集 \\w, \\W, \\b, \\B, \\d, \\D, \\s, \\S 依賴於 Unicode 字符屬性數據庫
  • re.X 為了增加可讀性,忽略空格和' # '後面的註釋

該函數根據包含的正則表達式的字符串創建模式對象

。可以實現更有效率的匹配。在直接使用字符串表示的正則表達式進行search,match和findall操作時,python會將字符串轉換為正則表達式對象。而使用compile完成一次轉換之後,在每次使用模式的時候就不用重複轉換。當然,使用re.compile()函數進行轉換後,re.search(pattern, string)的調用方式就轉換為 pattern.search(string)的調用方式。

特殊分組

正常我們是使用()來進行分組,這裡有兩個特殊的分組:命名組和非捕獲組

命名組格式為(?P<name>...),其中那麼是組的名字,...是內容.它可以通過group(name)來代替編號訪問,也可以通過編號來訪問./<name>

非捕獲組(?:...),它不能通過組方法訪問,所以將他們添加到現有的正則表達式中不會破壞編號.

python 正則表達式還記得嗎?來複習下吧

特殊序列

一個有用特殊的序列 是反斜槓和1到99之間的數字,例如\\1 表示匹配group(1)的表達式.

python 正則表達式還記得嗎?來複習下吧

這裡的(.+)分別匹配了ling和<that>.\\1表示(.+)匹配的第一組表達式就是ling和<that>.所以(.+) \\1表示ling ling ;<that><that>/<that>/<that>/<that>

關於正則表達式的詳情可以點擊這裡:


分享到:


相關文章: