8

I'm currently trying to use regular expressions in C#:

Regex reg_gameinfo = new Regex(@"PokerStars Game #(?<HID>[0-9]+):\s+(?:HORSE)? \(?(?<GAME>Hold'em|Razz|7 Card Stud|Omaha|Omaha Hi/Lo|Badugi) (?<LIMIT>No Limit|Limit|Pot Limit),? \(?(?<CURRENCYSIGN>\$|)?(?<SB>[.0-9]+)/\$?(?<BB>[.0-9]+) (?<CURRENCY>.*)\) - (?<DATETIME>.*$)", RegexOptions.Multiline);
Match matchresults = reg_gameinfo.Match(rawtext);
Dictionary<string,string> gameinfo = new Dictionary<string,string>();
if (matchresults.Success)
{
     gameinfo.Add("HID", matchresults.Groups["HID"].Value);
     gameinfo.Add("GAME", matchresults.Groups["GAME"].Value);
     ...
}

Can I iterate through the matchresult.Groups GroupCollection and add the key-value pairs to my gameinfo dictionary?

Palec
  • 12,743
  • 8
  • 69
  • 138
Sven
  • 2,839
  • 7
  • 33
  • 53

2 Answers2

13

(See this question: Regex: get the name of captured groups in C#)

You can use GetGroupNames:

Regex reg_gameinfo = new Regex(@"PokerStars Game #(?<HID>[0-9]+):\s+(?:HORSE)? \(?(?<GAME>Hold'em|Razz|7 Card Stud|Omaha|Omaha Hi/Lo|Badugi) (?<LIMIT>No Limit|Limit|Pot Limit),? \(?(?<CURRENCYSIGN>\$|)?(?<SB>[.0-9]+)/\$?(?<BB>[.0-9]+) (?<CURRENCY>.*)\) - (?<DATETIME>.*$)", RegexOptions.Multiline);
Match matchresults = reg_gameinfo.Match(rawtext);
Dictionary<string,string> gameinfo = new Dictionary<string,string>();

if (matchresults.Success)
    foreach(string groupName in reg_gameinfo.GetGroupNames())
        gameinfo.Add(groupName, matchresults.Groups[groupName].Value);  
Community
  • 1
  • 1
Johan Kullbom
  • 4,183
  • 26
  • 28
1

You could put the group names into a list and iterate over it. Something like

List<string> groupNames = ...
foreach (string g in groupNames) {
    gameinfo.Add(g, matchresults.Groups[g].Value);
}

But make sure to check whether the group exists.

Palec
  • 12,743
  • 8
  • 69
  • 138
Patrick
  • 1,328
  • 10
  • 19