Python's regular expression?
Duncan Booth
duncan.booth at invalid.invalid
Tue May 9 05:47:58 EDT 2006
Mirco Wahab wrote:
> If you wouldn't need dictionary lookup and
> get away with associated categories, all
> you'd have to do would be this:
>
> $PATTERN = qr/
> (blue |white |red )(?{'Colour'})
> | (socks|tights )(?{'Garment'})
> | (boot |shoe |trainer)(?{'Footwear'})
> /x;
>
> $t = 'blue socks and red shoes';
> print "$^R: $^N\n" while( $t=~/$PATTERN/g );
>
> What's the point of all that? IMHO, Python's
> Regex support is quite good and useful, but
> won't give you an edge over Perl's in the end.
If you are desperate to collapse the code down to a single print statement
you can do that easily in Python as well:
>>> PATTERN = '''
(?P<Colour>blue |white |red)
| (?P<Garment>socks|tights)
| (?P<Footwear>boot |shoe |trainer)
'''
>>> t = 'blue socks and red shoes'
>>> print '\n'.join("%s:%s" % (match.lastgroup,
match.group(match.lastgroup))
for match in re.finditer(PATTERN, t, re.VERBOSE))
Colour:blue
Garment:socks
Colour:red
Footwear:shoe
More information about the Python-list
mailing list