2009-10-15 13 views
8

Actualmente estoy tratando de utilizar expresiones regulares en C#:iteración a través 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); 
    ... 
} 

¿Puedo iterar a través de la matchresult.Groups GroupCollection y añadir los pares de valores clave a mi diccionario gameinfo?

Respuesta

12

(Véase esta pregunta: Regex: get the name of captured groups in C#)

Puede utilizar 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

Puede poner los nombres de grupos en una lista e iterar sobre ellos. Algo como

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

Pero asegúrese de comprobar si el grupo existe.

Cuestiones relacionadas