"Zeroing out" the Nth group in a RE

Greg Chapman glc at well.com
Mon Aug 5 10:04:52 EDT 2002


On Sun, 04 Aug 2002 22:05:30 +0300, Pekka Niiranen <krissepu at vip.fi> wrote:

>What is needed is version of SRE which re.findall() does not return empty matches!!!

SRE pattern objects have an undocumented scanner method, which returns an object
capable of repeatedly searching or matching over the given text.  This makes it
relatively easy to rewrite findall so that unmatched groups are returned as
None:

def scan_finditer(pattern, text):
    scanner = pattern.scanner(text)
    while True:
        m = scanner.search()
        if not m: break
        yield m

def scan_findall(pattern, text):
    iter = scan_finditer(pattern, text)
    if pattern.groups > 0:
        return [m.groups() for m in iter]
    else:
        return [m.group(0) for m in iter]

---
Greg Chapman




More information about the Python-list mailing list