2009-10-15 9 views
8

मैं वर्तमान में सी # में रेगुलर एक्सप्रेशन का उपयोग करने के लिए कोशिश कर रहा हूँ के माध्यम से:पुनरावृत्ति सी # में 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); 
} 

लेकिन यह सुनिश्चित करना सुनिश्चित करें कि समूह मौजूद है या नहीं।

संबंधित मुद्दे