Python regex get group position

You need to reference the group number:

>>> import re
>>>
>>> a = '/afolder_l/location/folder_l/file.jpg'
>>> p= re.compile("/.+/location/.+_([lr])/")
>>> m = p.match(a)
>>> m.span()
(0, 29)
>>> m.span(1)
(27, 28)

You can use .span() method of SRE_Match object with integer argument input as a group number.

Some examples for more clarity. If you use 3 groups of () so the group 0 will be the full matched, and with argument input as integer number from 1 to 3 will be the matched and index of each group number with .group() and .span() method, respectively. Hope this helps!

>>> import re
>>> regex = re.compile(r"(\d{4})\/(\d{2})\/(\d{2})")
>>> text = "2019/12/31"
>>> matched = regex.match(text)
>>> matched
<_sre.SRE_Match object; span=(0, 10), match='2019/12/31'>

>>> matched.groups()
('2019', '12', '31')
>>> matched.span()
(0, 10)

>>> matched.group(0)
'2019/12/31'
>>> matched.span(0)
(0, 10)

>>> matched.group(1)
'2019'
>>> matched.span(1)
(0, 4)

>>> matched.group(2)
'12'
>>> matched.span(2)
(5, 7)

>>> matched.group(3)
'31'
>>> matched.span(3)
(8, 10)

Tags:

Python

Regex