我有一个正则表达式来检查我的字符串。在我的字符串中,我有两组 ?<key>和 ?<value> .所以这是我的示例字符串:
string input = "key=value&key=value1&key=value2";
我使用 MatchCollections当我尝试在控制台上打印我的组时,这是我的代码:
string input = Console.ReadLine();
string pattern = @"(?<key>\w+)=(?<value>\w+)";
Regex rgx = new Regex(pattern);
MatchCollection matches = rgx.Matches(input);
foreach (Match item in matches)
{
Console.Write("{0}=[{1}]",item.Groups["key"], item.Groups["value"]);
}
我得到这样的输出: key=[value]key=[value1]key=[value2]
但我希望我的输出是这样的: key=[value, value1, value2]
我的观点是如何检查组“key”是否与前一个组相同,这样我就可以按照我想要的方式输出。
请您参考如下方法:
您可以使用 Dictionary<string, List<string>> :
string pattern = @"(?<key>\w+)=(?<value>\w+)";
Regex rgx = new Regex(pattern);
MatchCollection matches = rgx.Matches(input);
Dictionary<string, List<string>> results = new Dictionary<string, List<string>>();
foreach (Match item in matches)
{
if (!results.ContainsKey(item.Groups["key"].Value)) {
results.Add(item.Groups["key"].Value, new List<string>());
}
results[item.Groups["key"].Value].Add(item.Groups["value"].Value);
}
foreach (var r in results) {
Console.Write("{0}=[{1}]", r.Key, string.Join(", ", r.Value));
}
注意 string.Join 的使用以要求的格式输出数据。
