multiple pattern regular expression

Robert Bossy Robert.Bossy at jouy.inra.fr
Fri Apr 25 09:00:43 EDT 2008


Arnaud Delobelle wrote:
> 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)
I might add before you stumble upon the consequences:
    params[name.rstrip()] = value.lstrip()

Cheers,
RB



More information about the Python-list mailing list