Skip to content Skip to sidebar Skip to footer

Re In Python - Lastindex Attribute

I'm writing tutorial about 'advanced' regular expressions for Python, and I cannot understand lastindex attribute. Why is it always 1 in the given examples: http://docs.python.or

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 ---")
ifmatch:
    printmatch.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.

printmatch.group(2)

Post a Comment for "Re In Python - Lastindex Attribute"