[regexp] Where's the error in this ini-file reading regexp?

John Hunter jdhunter at nitace.bsd.uchicago.edu
Wed Nov 13 15:55:26 EST 2002


>>>>> "F" == F GEIGER <fgeiger at datec.at> writes:
    F> rex = re.compile(r"(\s*(\[.+\])(\s*((.+)=(.+)))+?)",
    F> re.MULTILINE|re.IGNORECASE) L = rex.findall(s)

This is a little messier than necessary.  If the config file is really
as simple as the example, how about a dictionary of dictionaries?

import re
s = \
'''[Section 1]
Key11=Value11
Key12=Value12
Key13=Value13
[Section 2]
Key21=Value21
Key22=Value22
Key23=Value23'''


rgx = re.compile('^\[Section (\d+)\]$')

config = {}
for line in s.split('\n'):
    m = rgx.match(line)
    if m:
        secNum = int(m.group(1))
        continue
    try: secNum
    except NameError: raise RuntimeError, 'Improper config file, no section defined'
    else:
        key, val = line.split('=')
        config.setdefault(secNum, {})[key] = val

print config
        
The key value pairs in each section are calling for a string split.
All you have to do is keep tabs on the section number by updating it
when you see a match for a section regex.  The section numbers are
keys for the dictionary, and each key points to a dictionary of
key/value pairs for that section.

Simple, clean, easy to read and it works.

You can get the vals with, eg, 

config[1]['Key11']

JDH




More information about the Python-list mailing list