Icon Style Pattern Matching in Python |
This is the Icon example translated into Python using an implementation based on operator overloading:
from string import uppercase, digits postalcode = "H3G 1V7" if postalcode ^ (AnyOfP(uppercase) & AnyOfP(digits) & \ AnyOfP(uppercase)) >> "part1" & \ IsP(" ") [0:1] & \ (AnyOfP(digits) & AnyOfP(uppercase) & \ AnyOfP(digits)) >> "part2" & AtTheEndP(): postalcode = lastMatch() ["part1"] + \ lastMatch() ["part2"] print postalcode else: print "Invalid postalcode", postalcode