c# - 如何检查正则表达式组是否相等?

标签 c# .net regex match

我有一个正则表达式来检查我的字符串。在我的字符串中,我有两组 ?<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 的使用以要求的格式输出数据。

关于c# - 如何检查正则表达式组是否相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30328449/

相关文章:

C# 代码仅在单步执行时给出预期结果?

c# - 使用NEST客户端将过滤器添加到elasticsearch的搜索查询中

c# - 如何导航到另一个项目的 View

c# - "Elegant"从对象的 List<T> 中获取属性值列表的方法?

regex - 如何在 Ant 中获取正则表达式匹配的 bool 结果?

c# - Razor页面如何找到DisplayNameFor中的字段?

c# - 三元最佳实践

.net - 如何在自定义控件上添加对 Point 属性的设计器支持?

regex - 使用 perl 增加文本文件中的数字

java - 包含单词但不包含其前面的特定单词