Using regular expressions to parse INI file

  • Thread starter Thread starter Marc Scheuner [MVP ADSI]
  • Start date Start date
M

Marc Scheuner [MVP ADSI]

Folks,

I was trying to parse standard Windows INI files using regular
expressions, but I can't seem to get it to work all the way....

I have two tasks, basically:

* retrieve all the section names (names between [....])

* given a section, retrieve all its key=value strings

I can achieve goal no. 1 by having a regular expression of
"\[(?<section>(.*))\].*". This seems to work okay - I can load the INI
file into a string, and apply that regex to it, and iterating over all
the .Matches and looking at the Match.Groups["section"].Value entries,
I get my section names:

StreamReader oSR = new StreamReader(<name of my INI file>);
string strINIFile = oSR.ReadToEnd();
oSR.Close();

// grab all the section names by means of a regular expression
MatchCollection oMatches = Regex.Matches(strINIFile,
@"\[(?<section>(.*))\].*");

foreach(Match oMatch in oMatches)
{
string sConfSection = oMatch.Groups["section"].Value;
// do something with sConfSection
}

However, I can't seem to get any regular expression working that would
pick out all the key=value pairs for me, from a given section. I
figured I'd just search for the "[section]" token, and then grab
anything up to the next "[" character - but I can't seem to get that
working.....

Any ideas???

Marc

================================================================
Marc Scheuner May The Source Be With You!
Bern, Switzerland m.scheuner(at)inova.ch
 
I think you could use something like

\[(?<section>(.*))\]\n
(?<key_value_pairs>(?<key>[^=[]*)=(?<value>[^\n]*)\n)*

to get a whole section at once, and then use the Group's Captures-property
to retrieve the "key_value_pairs" one by one. (note that this regex won't
handle comments and newlines correctly, but using a good RegEx tool like
expresso or regulator, that should be entirely possible)

Of course, you could also first use RegEx.split to split the ini string into
section substrings, and parse each of them with a simpler regex.

Niki
 
Back
Top