将Regex.Matches连接到一个字符串

200*_*L.B 5 .net c# 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";
Run Code Online (Sandbox Code Playgroud)

应用匹配模式以提取以main开头的所有字符串.返回

Regex regex = new Regex("main.[^=]+=[^=;]+");       
MatchCollection matchCollection = regex.Matches(str);
Run Code Online (Sandbox Code Playgroud)

我试过这个来连接匹配集合

string flatchain = string.Empty;
foreach (Match m in matchCollection)
{
    flatchain = flatchain +";"+ m.Value; 
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来使用LINQ?

BRA*_*mel 10

您可以尝试将结果转换为数组并应用string.Join将字符串放在平面中,您必须明确指定Match类型,因为它MatchCollection是一个non-generic IEnumerable类型

  var toarray = from Match match in matchCollection select match.Value;
                string newflatChain = string.Join(";", toarray); 
Run Code Online (Sandbox Code Playgroud)

或者如果你只想要一行,你可以像下面这样做

string newflatChain = string.Join(";", from Match match in matchCollection select match.Value);
Run Code Online (Sandbox Code Playgroud)


Geo*_*org 8

作为单线,这将是

var flatchain = string.Join(";", matchCollection.Cast<Match>().Select(m => m.Value));
Run Code Online (Sandbox Code Playgroud)

转换的原因是MatchCollection仅实现旧的非通用IEnumerable版本.