gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:57:18 24 4
gpt4 key购买 nike

这是我在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com