[英]python regex search findall capturing groups
我只想獲取“ 66664324”,即“)”和“-”之間的內容。 為什么search
方法會自己獲取“)”和“-”。
a="(021)66664324-01"
b1=re.findall('\)(.*)-',a)
>['66664324']
b2=re.search('\)(.*)-',a).group()
>')66664324-'
這兩個代碼段之間有什么區別。
嘗試在re.search
打印group(1)而不是group()。 其中group()
打印整個匹配項,而group(1)僅打印捕獲的組1( 組索引1內部存在的printig字符 )。
>>> a="(021)66664324-01"
>>> import re
>>> b2=re.search('\)(.*)-',a).group(1)
>>> b2
'66664324'
>>> b2=re.search('\)(.*)-',a).group()
>>> b2
')66664324-'
但是re.findall
優先考慮組而不是匹配項,並且它返回列表中的結果,但search
沒有。 這樣b1=re.findall('\\)(.*)-',a)
為您提供所需的輸出。 如果存在一個組,則re.findall
方法將僅打印不匹配的組。 如果沒有組,則僅打印匹配項。
>>> b1=re.findall('\)(.*)-',a)
>>> b1
['66664324']
>>> b1=re.findall('\).*-',a)
>>> b1
[')66664324-']
區別在於b2.group(),等於b2.group(0)。 並基於python regex手冊
模式的search()方法掃描字符串,因此在這種情況下,匹配可能不會從零開始
因此,在您的情況下,結果從索引1開始。我已經嘗試對您的代碼進行一些修改,對搜索規則進行了修改,預期結果在索引1處。
>>> a =“(021)66664324-01”
>>> re.search('\\)([0-9] *)',a).group(1)
'66664324'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.