String pattern matching

Kent Johnson kent at kentsjohnson.com
Mon Apr 3 13:45:29 EDT 2006


Jim Lewis wrote:
> Anyone have experience with string pattern matching?
> I need a fast way to match variables to strings. Example:
> 
> string - variables
> ============
> abcaaab - xyz
> abca - xy
> eeabcac - vxw
> 
> x matches abc
> y matches a
> z matches aab
> w maches ac
> v maches ee
> 

You can do this with a regular expression, actually:

testText = '/abcaaab/abca/eeabcac/'
import re

m = 
re.search(r'/(?P<x>.+)(?P<y>.+)(?P<z>.+)/(?P=x)(?P=y)/(?P<v>.+)(?P=x)(?P<w>.+)/', 
testText)
print m.group('v', 'w', 'x', 'y', 'z')


Output is:
('ee', 'ac', 'abc', 'a', 'aab')

For variety, change the matches to non-greedy (.+?) and get this result:
('ee', 'bcac', 'a', 'bca', 'aab')


Kent



More information about the Python-list mailing list