我目前正在尝试在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);
...
}
我可以遍历matchresult.Groups
GroupCollection并将键值对添加到我的gameinfo
字典中吗?
答案 0 :(得分:13)
(见这个问题: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 :(得分:1)
您可以将组名放入列表中并对其进行迭代。像
这样的东西List<string> groupNames = ...
foreach (string g in groupNames) {
gameinfo.Add(g, matchresults.Groups[g].Value);
}
但请务必检查该组是否存在。