我有以下代码生成MatchCollection:
var tmp3 = myregex.Matches(text_to_split);
Run Code Online (Sandbox Code Playgroud)
在Matches在tmp3都是字符串,如93.4和-276.2.我真正需要的是将此MatchCollection转换为双精度数组.如何才能做到这一点?
您可以使用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和函数式编程风扇,您可以保存一个无用的循环并直接转换MatchCollection为IEnumerable<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方法,但如果你的正则表达式是不够好,你已确保该字符串是你应该确定一个合适的格式.