RE In Python - Lastindex Attribute
Solution 1:
lastindex
is the index of the last group that matched. The examples in the documentation include one that uses 2 capturing groups:
(a)(b)
where lastindex
is set to 2 as the last capturing group to match was (b)
.
The attribute comes in handy when you have optional capturing groups; compare:
>>> re.match('(required)( optional)?', 'required').lastindex
1
>>> re.match('(required)( optional)?', 'required optional').lastindex
2
When you have nested groups, the outer group is the last to match. So with ((ab))
or ((a)(b))
the outer group is group 1 and the last to match.
Solution 2:
In regex groups are captured using ()
. In python re
the lastindex
holds the last capturing group.
Lets see this small code example:
match = re.search("(\w+).+?(\d+).+?(\W+)", "input 123 ---")
if match:
print match.lastindex
In this example, the output will be 3 as I have used three ()
in my regex and it matched all of those.
For the above code, if you execute the following line in if
block, it will output 123
as it is the second capture group.
print match.group(2)
Post a Comment for "RE In Python - Lastindex Attribute"