我寫的Python, 「先進」 的正則表達式的教程,我無法理解RE在Python - lastIndex的屬性
lastindex
屬性。爲什麼總是1給出的例子: http://docs.python.org/2/library/re.html#re.MatchObject.lastindex
我的意思是這個例子:
re.match('((ab))', 'ab').lastindex
爲什麼是1?第二組也是匹配的。
我寫的Python, 「先進」 的正則表達式的教程,我無法理解RE在Python - lastIndex的屬性
lastindex
屬性。爲什麼總是1給出的例子: http://docs.python.org/2/library/re.html#re.MatchObject.lastindex
我的意思是這個例子:
re.match('((ab))', 'ab').lastindex
爲什麼是1?第二組也是匹配的。
lastindex
是匹配的最後一組的索引。文檔中的實例包括一種使用2個捕獲組:
(a)(b)
其中lastindex
被設置爲2作爲最後捕獲組來匹配是(b)
。
當您有可選的捕獲組時,該屬性會派上用場;比較:
>>> re.match('(required)(optional)?', 'required').lastindex
1
>>> re.match('(required)(optional)?', 'required optional').lastindex
2
當你有嵌套組,外組是最後的匹配。因此,((ab))
或((a)(b))
外部組是組1和最後匹配。
您的解釋清晰直觀。但我不明白從返回1的文檔中得到的例子。我剛剛更新了我的問題。 –
如果我有像您說的那樣的「可選捕獲組」,我會使用MatchObject.group(number),如果不匹配,則返回None。 lastindex屬性必須爲其他東西... –
@TomekWyderka:當然,但你問什麼'lastindex'的意思。 –
正則表達式組使用()
捕獲。在python re
lastindex
擁有最後一個捕獲組。
讓我們來看看這個小的代碼示例:
match = re.search("(\w+).+?(\d+).+?(\W+)", "input 123 ---")
if match:
print match.lastindex
在這個例子中,輸出將是3,因爲我已經使用了三個()
在我的正則表達式,它匹配所有這些。
對於上面的代碼,如果在if
塊中執行以下行,它將輸出123
,因爲它是第二個捕獲組。
print match.group(2)
請查看我添加到我的問題的示例。 –
不,在給出的例子中是1或2。 –