2009-10-15 8 views
8

J'essaie actuellement d'utiliser des expressions régulières en C#:Iteration par GroupCollection en 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); 
    ... 
} 

Puis-je itérer le matchresult.Groups GroupCollection et ajoutez les paires clé-valeur à mon gameinfo dictionnaire?

Répondre

12

(Voir cette question: Regex: get the name of captured groups in C#)

Vous pouvez utiliser 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); 
1

Vous pouvez mettre les noms de groupe dans une liste et les parcourir. Quelque chose comme

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

Mais assurez-vous de vérifier si le groupe existe.

Questions connexes