C# 如何检查正则表达式组是否相等?
我有一个正则表达式来检查我的字符串。在我的字符串中有两个组C# 如何检查正则表达式组是否相等?,c#,.net,regex,match,C#,.net,Regex,Match,我有一个正则表达式来检查我的字符串。在我的字符串中有两个组?和?。下面是我的示例字符串: string input = "key=value&key=value1&key=value2"; 我使用MatchCollections在控制台上打印我的组时,我的代码如下: string input = Console.ReadLine(); string pattern = @"(?<key>\w+)=(?<value>\w+)"; Regex rgx = n
?
和?
。下面是我的示例字符串:
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"]);
}
string input=Console.ReadLine();
字符串模式=@“(?\w+)=(?\w+);
正则表达式rgx=新正则表达式(模式);
MatchCollection matches=rgx.matches(输入);
foreach(匹配项中的匹配项)
{
Console.Write(“{0}=[{1}]”,item.Groups[“key”],item.Groups[“value”]);
}
我得到如下输出:key=[value]key=[value1]key=[value2]
但我希望我的输出是这样的:key=[value,value1,value2]
我的重点是如何检查组“键
”是否与前一个相等,以便我可以按照我想要的方式进行输出 使用字典
比如:
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);
}
var dict=newdictionary();
foreach(匹配项中的匹配项)
{
var key=item.Groups[“key”];
var val=项目组[“值”];
如果(!dict.ContainsKey(键))
{
dict[key]=新列表();
}
dict[key].Add(val);
}
您可以使用LinqGroupBy
方法:
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));
}
您可以使用
词典
:
字符串模式=@“(?\w+)=(?\w+);
正则表达式rgx=新正则表达式(模式);
MatchCollection matches=rgx.matches(输入);
字典结果=新字典();
foreach(匹配项中的匹配项)
{
如果(!results.ContainsKey(item.Groups[“key”].Value)){
添加(item.Groups[“key”].Value,新列表());
}
结果[item.Groups[“key”].Value]。添加(item.Groups[“Value”].Value);
}
foreach(结果中的var r){
Write(“{0}=[{1}]”,r.Key,string.Join(“,”,r.Value));
}
请注意使用
string.Join
以所需格式输出数据。我已编辑了您的标题。请参阅“”,其中的共识是“不,他们不应该”。在Java世界中,我想我会存储在映射中,然后根据该映射生成一个字符串。我想你的问题超出了正则表达式的范围,你需要做一些处理,但我可能错了。是的。我想在控制台上打印它,让它看起来像字典“Key”=[“value”、“value1”、“value2”]
key=[value,value1,value2]
key1=[value3,value4]
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));
}