searching backwards in a string
Mark McEahern
marklists at mceahern.com
Tue Feb 12 09:55:46 EST 2002
[Paul Rubin]
> I have a string and want to search backwards for a regexp, starting at
> a given index, like if you search backwards in a text editor. Is
> there a way to do that with re? The docs aren't clear about what's
> supposed to happen if the ending position to the pat.search method is
> less than the starting position, but I tried it and it doesn't seem
> to do what I want. Any advice appreciated--thanks.
Short answer: Reverse the string first.
Sample:
#! /usr/bin/env python
# findBackwards.py
import re
def reverseWord(s):
l = list(s)
l.reverse()
return ''.join(l)
def findBackwards(s, pattern):
"""Return the location of the first match of pattern in s, searching
backwards."""
r = reverseWord(s)
m = re.search(pattern, r)
if m is None:
print "%s not found in %s." % (pattern, s)
return
# Express location relative to original orientation of word.
start = len(s) - m.start()
print "%s found backwards in %s at %d." % (pattern, s, start)
s = "foobar"
pattern = "o"
findBackwards(s, pattern)
pattern = "z"
findBackwards(s, pattern)
Running:
$ findBackwards.py
o found backwards in foobar at 3.
z not found in foobar.
More information about the Python-list
mailing list