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

标签 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(str);

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

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

使用 LINQ 是否有更好的方法?

最佳答案

您可以尝试将结果转换为数组并应用 string.Join 将字符串平放 此处您必须明确指定 Match 类型,因为 MatchCollectionnon-generic 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);

关于c# - 将 Regex.Matches 连接到一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21510155/

相关文章:

c# - 易趣 API : How do I specify "Standard Shipping (FedEx Ground or FedEx Home Delivery®)" as a shipping service?

c# - 为 JWT 生成 key ?

regex - 如何在 VBA 字符串中查找字母和数字的组合?

java - 使用表达式语言检索带引号的字符串

c# - 在 C# 中,您可以为具有名称的值元组定义别名吗?

c# - Matrix.RotateAt 方法对于某些角度是否存在错误? .Net Winforms

C# - 使用 WebImage.GetImageFromRequest() 进行多次上传

JavaScript 正则表达式 : How to pluck certain matches out of string?

c# - Entity Framework 6 : Insert or Update

c# - 使用 ImageSharp 从 byte[] 创建图像