Extracting/finding strings from a list

vincent wehren vincent at visualtrans.de
Mon Jul 19 07:01:16 CEST 2004

Steve wrote:
> Hi,
> I have a very long string, someting like:
>         DISPLAY=localhost:0.0,FORT_BUFFERED=true,
> F_ERROPT1=271\,271\,2\,1\,2\,2\,2\,2,G03BASIS=/opt/g03b05/g03/basis,
>         GAMESS=/opt/gamess,GAUSS_ARCHDIR=/opt/g03b05/g03/arch,
> GAUSS_EXEDIR=/opt/g03b05/g03/bsd:/opt/g03b05/g03/private:/opt/g03b05/g
>         03,GAUSS_SCR_ROOT=/home/561/345561/scratch,
>         GDVBASIS=/opt/g03b05/g03/basis,
> and I need to extract the value of the variable "GAUSS_EXEDIR". Although 
> these are environment variables, I don't have access to them directly. 
> These variables are stored in a special file and I need to parse it to 
> be able to extract the variable. I wrote the following code for this:
>                 ...

How about a little RE:

import re

search_string = file("./somefile").read()
patt = """(?P<key>GAUSS_EXEDIR)

compile_obj = re.compile(patt,  re.IGNORECASE| re.DOTALL| re.VERBOSE)
match_obj = compile_obj.search(search_string)

# to search for the first match:
if match_obj:
     value = match_obj.group('value')
     print value

# to find all matches:
match_obj = compile_obj.findall(search_string)
for match in match_obj:
     value = match[2]
     print value

Vincent Wehren

More information about the Python-list mailing list