Reputation: 13
The example:
r = re.search("a(..)d(.)f", "xxabcdefg")
r.span()
returns (2, 8)
the entire string
but I would like to get the start and end positions of the two captured groups, so (2, 4)
and (6, 7)
.
Upvotes: 0
Views: 59
Reputation: 1121962
The r.span()
method takes a group parameter; each group is numbered, so use 1
and 2
to get the spans of the two groups, 0
for the whole text (where 0
is the default):
>>> import re
>>> r = re.search("a(..)d(.)f", "xxabcdefg")
>>> r.span()
(2, 8)
>>> r.span(1)
(3, 5)
>>> r.span(2)
(6, 7)
From the MatchObject.span()
method documentation:
span([group])
ForMatchObject
m, return the 2-tuple(m.start(group), m.end(group))
. Note that if group did not contribute to the match, this is(-1, -1)
. group defaults to zero, the entire match.
Upvotes: 2