matching and extracting...

Cliff Wells LogiplexSoftware at earthlink.net
Wed Jan 15 01:29:30 CET 2003


On Tue, 2003-01-14 at 16:14, Cliff Wells wrote:

[blah blah, snip]


This is a couple of lines shorter and now my design is perfect <wink>:

import re

class matchseq:
    def __init__(self, sequence):
        self.items = []
        exp = ""
        for item in sequence.split():
            if exp:
                exp += " "
            k, v = item.split('-')
            exp += "(?P<%s>%s)" % (k, ["\D*\d*", k][v == 'p'])
            if v == 'x':
                self.items.append(k)

        self.re = re.compile(exp)
                
    def match(self, sequence):
        match = self.re.match(sequence)
        results = {}
        if match:
            for k in self.items:
                results[k] = match.group(k)
        return results


m = matchseq("a0-p i1-x i2-x i3-? a4-p i5-x i6-? i7-x i8-?")

result = m.match("a1 a1 a2 a3 a4 a5 a6 a7 a8")
if result:
    print result
    
result = m.match("a0 a1 a2 a3 a4 a5 a6 a7 a8")
if result:
    print result


-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308






More information about the Python-list mailing list