聲明:本文所使用方法為老猿自行研究并編碼,相關代碼版權為老猿所有,禁止轉載文章,代碼禁止用于商業(yè)用途!
在《第11.23節(jié) Python 中re模塊的搜索替換功能:sub及subn函數(shù)》介紹了re.sub函數(shù),其中的替換內容可以是一個函數(shù),利用該功能我們可以展示正則表達式匹配過程中匹配到的目標子串的匹配順序、匹配文本的內容和匹配文本在搜索文本中的位置。具體實現(xiàn)如下:
import re
matchcount = 0
def parsematch(patstr,text):
global matchcount
matchcount = 0
re.sub(patstr,matchrsult,text)
def matchrsult(m):
global matchcount
matchcount += 1
print(f"第{matchcount}次匹配,匹配情況:")
if(m.lastindex):
for i in range(0,m.lastindex+1):print(f" 匹配子串group({i}): {m.group(i)},位置為:{m.span(i)}") #正則表達式為{m.re},搜索文本為{m.string},
else:print(f" 匹配子串group(0): {m.group(0)},位置為:{m.span(0)}")
return m.group(0)
調用舉例:
>>> parsematch(r'(?i)(?P<lab>py\w*)','Python?PYTHON!Learning python with LaoYuan! ')
第1次匹配,匹配情況:
匹配子串group(0): Python,位置為:(0, 6)
匹配子串group(1): Python,位置為:(0, 6)
第2次匹配,匹配情況:
匹配子串group(0): PYTHON,位置為:(7, 13)
匹配子串group(1): PYTHON,位置為:(7, 13)
第3次匹配,匹配情況:
匹配子串group(0): python,位置為:(23, 29)
匹配子串group(1): python,位置為:(23, 29)
>>>
>>> parsematch('(.?)*',"abc")
第1次匹配,匹配情況:
匹配子串group(0): abc,位置為:(0, 3)
匹配子串group(1): ,位置為:(3, 3)
第2次匹配,匹配情況:
匹配子串group(0): ,位置為:(3, 3)
匹配子串group(1): ,位置為:(3, 3)
>>>
>>> parsematch('(?P<l1>Lao)(?P<l2>\w+)(Python)','LaoYuanPython')
第1次匹配,m.lastindex=3,匹配情況:
匹配子串group(0): LaoYuanPython,位置為:(0, 13)
匹配子串group(1): Lao,位置為:(0, 3)
匹配子串group(2): Yuan,位置為:(3, 7)
匹配子串group(3): Python,位置為:(7, 13)
>>>
不過上述分析過程僅用于多次搜索到目標串的時候才有作用,如果只是一次匹配到一個目標串,則無需使用該方法,因為使用匹配對象就很方便的查看匹配信息。
老猿Python,跟老猿學Python!
博客地址:https://blog.csdn.net/LaoYuanPython
請大家多多支持,點贊、評論和加關注!謝謝!