2009-10-15 52 views
8

我目前正試圖在C#中使用正則表達式:迭代通過C#GroupCollection

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); 
    ... 
} 

我可以通過matchresult.Groups GroupCollection迭代和鍵值對添加到我的gameinfo字典?

回答

12

(見這個問題:Regex: get the name of captured groups in C#

您可以使用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

您可以將組名稱放入列表中並對其進行迭代。像

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

但一定要檢查組是否存在。