multiple pattern regular expression

Nick Stinemates nick at stinemates.org
Fri Apr 25 18:52:47 EDT 2008


On Fri, Apr 25, 2008 at 09:50:56AM -0400, python at bdurham.com wrote:
> How about this?
> 
> for line in file:
>     # ignore lines without = assignment
>     if '=' in line:
>         property, value = line.strip().split( '=', 1 )
>         property = property.strip().lower()
>         value = value.strip()
> 
>         # do something with property, value
> 
> Malcolm
> --
> http://mail.python.org/mailman/listinfo/python-list

This works until you have:
string=The sum of 2+2=4

For cases where such input my be expected, I use the following regex

import re
str = """a=b
c=d
e=f
string=The sum of 2+2=4""".split("\n")

p = re.compile("([^=]*)=(.*)")

for lines in str:
	key,value=p.findall(lines)[0]
	print key, value


-- 
Nick Stinemates (nick at stinemates.org)
http://nick.stinemates.org



More information about the Python-list mailing list