tags:

views:

94

answers:

3

I have a regular expression which pulls name value pairs

([^=;]*)=([^;]*)

"Data Source=server;Initial Database=myDB;foo=bar;"

That works fine and I can get to the first result using

m.Groups[0] // "Data Source=server"
m.Groups[1] // "Data Source"
m.Groups[2] // "Server"

How do I get to the second and third set of matches? My terminology is probably wrong, I would appreciate help with that as well.

Thanks!

+3  A: 
Regex r = new Regex("([^=;]*)=([^;]*)");

MatchCollection mc = r.Matches("Data Source=server;Initial Database=myDB;foo=bar;");

foreach (Match m in mc)
{
    Console.WriteLine(m.Groups[0]);
    Console.WriteLine(m.Groups[1]);
    Console.WriteLine(m.Groups[2]);
}
Sean Bright
A: 

Match.NextMatch() method might be what you're looking for:

     string text = "Data Source=server;Initial Database=myDB;foo=bar;";

     Regex re = new Regex("([^=;]*)=([^;]*)");

     var m = re.Match(text);

     while (m.Success)
     {
        Console.Out.WriteLine("variable: {0} equals {1}", m.Groups[1], m.Groups[2]);
        m = m.NextMatch();
     }

See this MSDN page for a more complete code sample

Hamish Smith
+1  A: 

As eschneider pointed out, a regular expression in this case is a bit of overkill. TIMTOWTDI

string thestring ="Data Source=server;Initial Database=myDB;foo=bar;";

var keyVals = from kv in thestring.Split(new string[] { ";" },  StringSplitOptions.RemoveEmptyEntries)
select new KeyValuePair<string,string>(kv.Split('=')[0],kv.Split('=')[1]);

foreach (var keyVal in keyVals) {
  Console.WriteLine(keyVal.Key);
  Console.WriteLine(keyVal.Value);
}
aquinas
Thanks - nice to know the easy way to do things...
Sam