如何检查一个正则表达式组是否相等

本文关键字:正则表达式 一个 是否 何检查 检查 | 更新日期: 2023-09-27 17:50:01

我有一个RegEx检查我的字符串。在我的弦中,我有两组?<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以所需的格式输出数据

使用Dictionary<string,List<string>>

类似:

var dict = new Dictionary<string,List<string>>();
foreach (Match item in matches)
{
    var key = item.Groups["key"];
    var val = item.Groups["value"];
    if (!dict.ContainsKey(key)) 
    {
        dict[key] = new List<string>();
    }
    dict[key].Add(val);
}

您可以使用Linq GroupBy方法:

string input = "key=value&key=value1&key=value2&key1=value3&key1=value4";
string pattern = @"(?<key>'w+)=(?<value>'w+)";
Regex rgx = new Regex(pattern);
MatchCollection matches = rgx.Matches(input);
foreach (var result in matches
                         .Cast<Match>()
                         .GroupBy(k => k.Groups["key"].Value, v => v.Groups["value"].Value))
{
    Console.WriteLine("{0}=[{1}]", result.Key, String.Join(",", result));
}

代码片段的输出(这里我在原始输入字符串中添加了另一个带有两个值的键key1):

key=[value,value1,value2]
key1=[value3,value4]
相关文章: