这是我的代码:
a = '/afolder_l/location/folder_l/file.jpg'
p= re.compile("/.+/location/.+_([lr])/")
m = p.match(a)
现在,print m.group(1)会输出l,但我也想要该组的位置。目前,m.span()返回一个包含所有文本位置的元组。如何只获取'l'的位置?或者说,因为这是我正在分组的内容,所以怎样才能获取'r'的位置呢?
您需要引用组号:
>>> 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)
>>> 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)