String pattern matching

Eddie Corns eddie at holyrood.ed.ac.uk
Mon Apr 3 14:36:22 EDT 2006


Kent Johnson <kent at kentsjohnson.com> writes:

>Eddie Corns wrote:

>> If I get time I'll try to get this working in Sam Wilmott's Python pattern
>> matching library.
>> 
>> What fun!

>Cool! I have to get in on the fun :-)

>This program uses Sam Wilmott's library to find one solution. It is a 
>simple translation of your program above. I couldn't figure out how to 
>get multiple solutions.

Nice!

FWIW,
import string
from patterns_b import *

# investigate captured text and force a failure for backtracking.
# A bit clumsy perhaps! passing a lambda would be more elegant.
class DumpP (Pattern):
    def Match (self, subject):
        print 
        print 'v =', subject['v']
        print 'w =', subject['w']
        print 'x =', subject['x']
        print 'y =', subject['y']
        print 'z =', subject['z']
        if 1 == 2: yield None

subject = MatchingInput ('/abcaaab/abca/eeabcac/')
Letters = AnyOfP(string.letters)[1:]

while True:
    subject ^ FenceP() & IsP('/') & Letters >> 'x' & Letters >> 'y' & Letters >> 'z' & IsP('/') \
             & AnotherP('x') & AnotherP('y') & IsP('/') \
             & Letters >> 'v' & AnotherP('x') & Letters >> 'w' & IsP('/') & DumpP()


Not sure if it's supposed to exit in quite the way it does.

With a more compact notation, I think this beats regexs for many uses
especially when dealing with end users.

Note: if anyone else plays with this interesting pattern library, note there
are a couple of small bugs in it.

Eddie



More information about the Python-list mailing list