我写的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。 –