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

F. GEIGER fgeiger at datec.at
Thu Nov 14 02:36:39 EST 2002


I know, I could do it line-wise. But I am after a single re-line, doing
everything for me.

Thanks for your response!

Kind regards
Franz

"John Hunter" <jdhunter at nitace.bsd.uchicago.edu> schrieb im Newsbeitrag
news:mailman.1037220985.2546.python-list at python.org...
> >>>>> "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