将MatchCollection转换为双精度数组

Ada*_*m S 0 c# regex

我有以下代码生成MatchCollection:

var tmp3 = myregex.Matches(text_to_split);
Run Code Online (Sandbox Code Playgroud)

Matchestmp3都是字符串,如93.4-276.2.我真正需要的是将此MatchCollection转换为双精度数组.如何才能做到这一点?

Dar*_*rov 5

您可以使用double.Parse方法将字符串转换为double:

var tmp3 = myregex.Matches(text_to_split);
foreach (Match match in tmp3)
{
    double value = double.Parse(match.Value);
    // TODO : do something with the matches value
}
Run Code Online (Sandbox Code Playgroud)

如果您是像我这样的LINQ和函数式编程风扇,您可以保存一个无用的循环并直接转换MatchCollectionIEnumerable<double>:

var tmp3 = myregex.Matches(text_to_split);
var values = tmp3.Cast<Match>().Select(x => double.Parse(x.Value));
Run Code Online (Sandbox Code Playgroud)

如果您需要静态数组,则.ToArray()可能需要额外调用:

var tmp3 = myregex.Matches(text_to_split);
var values = tmp3.Cast<Match>().Select(x => double.Parse(x.Value)).ToArray();
Run Code Online (Sandbox Code Playgroud)

如果你想要一个安全的转换,你可以使用double.TryParse方法,但如果你的正则表达式是不够好,你已确保该字符串是你应该确定一个合适的格式.