Python正則表達式命名捕獲組和非捕獲組


命名捕獲組

的格式是 (?p<name>...),其中 name 是組的名稱,...是要匹配的表達式。它們的行為與正常組完全相同,除了可以通過索引訪問還可以通過 group(name) 方式訪問它們。非捕獲組的格式是 (?:...)

import re

pattern = r"(?P<python>123)(?:456)(789)"
string = "123456789"

match = re.match(pattern,string)

if match:
    print(match.group("python"))
    print(match.groups())
123
('123', '789')

非捕獲組

非捕獲組值匹配結果,但不捕獲結果,也不會分配組號,當然也不能在表達式和程序中做進一步處理。

import re

pattern = r"(?P<python>123)(?:456)(789)"
string = "123456789"

match = re.match(pattern,string)

if match:
    print(match.group("python"))#123
    print(match.groups())#('123', '789')

# 1.(?:pattern) : 匹配pattern,但不捕獲匹配結果
s="industryOpqindustries"
res=re.findall("industr(?:y|ies)",s)
print(res)#['industry', 'industries']
# 2.(?=pattern): 零寬度正向預查(正向零寬斷言),匹配后面跟的是pattern的內容,不匹配pattern,也不捕獲匹配結果。

s="windows2019windows2018windows1989"
res=re.sub("windows(?=2018|1989)","microsoft",s)
print(res)#windows2019microsoft2018microsoft1989

# 3. (?!pattern): 零寬度負向預查(負向零寬斷言),匹配后面跟的不是pattern的內容,不匹配pattern,不捕獲匹配結果。
res=re.sub("windows(?!2018|1989)","microsoft",s)
print(res)#microsoft2019windows2018windows1989

# 4.(?<=pattern): 零寬度正向回查(正向零寬斷言),匹配前面是pattern的內容,不匹配pattern,不捕獲匹配結果。
s="windows2019microfost2019"
res=re.sub("(?<=microfost)2019","pattern",s)
print(res)#windows2019microfostpattern

# 5.(?<!pattern): 零寬度負向回查(負向零寬斷言),匹配前面不是pattern的內容,不匹配pattern,不捕獲匹配結果。
res=re.sub("(?<!microfost)2019","pattern",s)
print(res)#windowspatternmicrofost2019

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM