我的应用程序似乎因“错误格式”而崩溃,我有这个:
Match m = Regex.Match(value, "[0-9]+[.[0-9]+]?");
double number = Convert.ToDouble(m.Value);
return number;
重点是使字符串值像这样:114.6W, 120.6W.
变成我可以排序的值。我编写的函数假设将任何字符串转换为 9999.9999 双精度值,但它在Convert.ToDouble()
. 输入格式错误?
我的应用程序似乎因“错误格式”而崩溃,我有这个:
Match m = Regex.Match(value, "[0-9]+[.[0-9]+]?");
double number = Convert.ToDouble(m.Value);
return number;
重点是使字符串值像这样:114.6W, 120.6W.
变成我可以排序的值。我编写的函数假设将任何字符串转换为 9999.9999 双精度值,但它在Convert.ToDouble()
. 输入格式错误?
问题出在你的正则表达式上:它应该是
[0-9]+(\.[0-9]+)?
[.[0.9]+]
(我对它的解析感到惊讶)是一个字符类,用于查找以下集合中的任何字符:点、开始和结束括号、0 到 9 或加号。
也许这.
不是您正在使用的文化的小数分隔符。InvariantCulture
解析时尝试指定:
double number = Convert.ToDouble(m.Value, CultureInfo.InvariantCulture);
Try these two regexes, you may need to test and adjust to your needs
this one will grab all numbers including the .
, but only if followed by a W (won't grab the w)
(?i)\d+\.\d+(?=w)
this one will grab all the digits regardless what's after it
\d+\.\d+
or if your data sets consists of only the numbers plus one letter and nothing in front or after it, do as @paul suggests, just strip the last char
您必须用括号替换方括号
Match m = Regex.Match(value, @"[0-9]+(?:\.[0-9]+)?");
如果保证始终是十进制数字后跟单个字母,则:
var word = "120.6W";
var d = Decimal.Parse(word.Substring(0,word.Length-1));