multiple pattern regular expression

Arnaud Delobelle arnodel at googlemail.com
Fri Apr 25 08:37:25 EDT 2008


micron_make <micro_passion at yahoo.com> writes:

> I am trying to parse a file whose contents are :
>
> parameter=current
> max=5A
> min=2A
>
> for a single line I used 
> for line in file:
> 	print re.search("parameter\s*=\s*(.*)",line).groups()
>
> is there a way to match multiple patterns using regex and return a
> dictionary. What I am looking for is (pseudo code)
>
> for line in file:
>    re.search("pattern1" OR "pattern2" OR ..,line)
>
> and the result should be {pattern1:match, pattern2:match...}
>
> Also should I be using regex at all here ?

If every line of the file is of the form name=value, then regexps are
indeed not needed.  You could do something like that.

params = {}
for line in file:
    name, value = line.strip().split('=', 2)
    params[name] = value 

(untested)
Then params should be the dictionary you want.

-- 
Arnaud



More information about the Python-list mailing list