re.rsearch?
Christophe Delord
christophe.delord at free.fr
Sun Jun 23 18:33:46 EDT 2002
Hi,
If you compile your pattern, you can give the pattern object a start position and an end position:
>>> p=re.compile("a")
>>> p.search("1a2a").span()
(1, 2)
>>> p.search("1a2a",2).span()
(3, 4)
This may work as you need:
def rsearch(reg, s):
start, end = None, None
i = 0
p = re.compile(reg)
while 1:
m = p.search(s, i)
if m:
start, end = m.span()
i = end
else:
break
return start, end
I found this in the documentation at http://web.pydoc.org/2.2/pre.html#RegexObject-search
--
search(self, string, pos=0, endpos=None)
search(string[, pos][, endpos]) -> MatchObject or None
Scan through string looking for a location where this regular
expression produces a match, and return a corresponding
MatchObject instance. Return None if no position in the string
matches the pattern; note that this is different from finding
a zero-length match at some point in the string. The optional
pos and endpos parameters have the same meaning as for the
match() method.
--
But of course as suggested by Fredrik Lundth, this solution is shorter:
def rsearch(reg, s):
return re.search("(?:.*)(%s)"%reg, s).span(1)
Best regards,
Christophe.
On 23 Jun 2002 21:42:54 GMT
quinn at baht.ugcs.caltech.edu (Quinn Dunkan) wrote:
> Occaisionally I find myself wanting an re.search that will find the rightmost
> match. In those occaisions, I use:
>
> def rsearch(reg, s):
> 'like re.search only find last match, return start, end instead of match'
> last_m = None
> start = end = 0
> while 1:
> m = re.search(reg, s[end:])
> if m is None:
> if last_m is None:
> return None, None
> else:
> return start, end
> last_m = m
> end += m.end()
> start = end - (m.end() - m.start())
>
> ... of course, it would be nicer to return an actual match object, but I
> haven't figured out how to do that short of faking up my own, and I've only
> needed (start, end) so far. Unfortunately, AFAIK, re.search also lacks a
> 'start_searching_at' type option.
>
> Has anyone else solved this probem in a more graceful way?
--
(o_ Christophe Delord _o)
//\ http://christophe.delord.free.fr/ /\\
V_/_ mailto:christophe.delord at free.fr _\_V
More information about the Python-list
mailing list