Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将Regex.Matches连接到字符串_C#_.net_Regex_Linq_C# 4.0 - Fatal编程技术网

C# 将Regex.Matches连接到字符串

C# 将Regex.Matches连接到字符串,c#,.net,regex,linq,c#-4.0,C#,.net,Regex,Linq,C# 4.0,这是我关于Stack的第一个问题 我有一根这样的绳子 string str = "key1=1;main.key=go1;main.test=go2;key2=2;x=y;main.go23=go23;main.go24=test24"; 应用于提取以main开头的所有字符串的匹配模式。返回 Regex regex = new Regex("main.[^=]+=[^=;]+"); MatchCollection matchCollection = regex.Matches(s

这是我关于Stack的第一个问题 我有一根这样的绳子

string str = "key1=1;main.key=go1;main.test=go2;key2=2;x=y;main.go23=go23;main.go24=test24";
应用于提取以main开头的所有字符串的匹配模式。返回

Regex regex = new Regex("main.[^=]+=[^=;]+");       
MatchCollection matchCollection = regex.Matches(str);
我已尝试将此连接到匹配集合

string flatchain = string.Empty;
foreach (Match m in matchCollection)
{
    flatchain = flatchain +";"+ m.Value; 
}

使用LINQ有更好的方法吗

您可以尝试将结果转换为数组并应用
字符串。Join
将字符串放在平面中 这里必须明确指定
Match
类型,因为
MatchCollection
非泛型IEnumerable
类型

  var toarray = from Match match in matchCollection select match.Value;
                string newflatChain = string.Join(";", toarray); 
或者,如果你只需要一行,你可以像下面这样做

string newflatChain = string.Join(";", from Match match in matchCollection select match.Value);

作为一艘客轮,这将是

var flatchain = string.Join(";", matchCollection.Cast<Match>().Select(m => m.Value));
var flatchain=string.Join(;),matchCollection.Cast().Select(m=>m.Value));

强制转换的原因是MatchCollection只实现旧的非通用IEnumerable版本。

只需使用LINQs
Aggregate
。例如:

var strIn = "key1=1;main.key=go1;main.test=go2;key2=2;x=y;main.go23=go23;main.go24=test24";

var strOut = Regex
             .Matches(str, "(main.[^=]+=[^=;]+)", RegexOptions.Multiline)
             .Cast<Match>()
             .Select(c => c.Value)
             .Aggregate(( a, b ) => a + ";" + b);
var strIn=“key1=1;main.key=go1;main.test=go2;key2=2;x=y;main.go23=go23;main.go24=test24”;
var strOut=Regex
.Matches(str,“(main.[^=]+=[^=;]+)”,RegexOptions.Multiline)
.Cast()
.选择(c=>c.Value)
.骨料((a,b)=>a+“;”+b);

注意:由于
Match
属性
Value
有一个私有setter,因此不能绕过LINQs
Select
,因为我们需要在聚合的lambda表达式中分配一个字符串。

看看我的答案