A vote for re scanner
Wade Leftwich
wade at lightlink.com
Sat Nov 15 10:36:18 EST 2003
Alex Martelli <aleax at aleax.it> wrote:
> Wade Leftwich wrote:
> ...
> > A scanner is constructed from a regex object and a string to be
> > scanned. Each call to the scanner's search() method returns the next
> > match object of the regex on the string. So to work on a string that
> > has multiple matches, it's the bee's roller skates.
>
> ...if that method's name was 'next' (and an appropriate __iter__
> also present) it might be even cooler, though...
>
>
> Alex
Indeed:
>>> class CoolerScanner(object):
... def __init__(self, regex, s):
... self.scanner = regex.scanner(s)
... def next(self):
... m = self.scanner.search()
... if m:
... return m
... else:
... raise StopIteration
... def __iter__(self):
... while 1:
... yield self.next()
...
>>> regex = re.compile(r'(?P<before>.)a(?P<after>.)')
>>> s = '1ab2ac3ad'
>>> for m in CoolerScanner(regex, s):
... print m.group('before'), m.group('after')
...
1 b
2 c
3 d
>>>
-- Wade
More information about the Python-list
mailing list