简体   繁体   English

使用正则表达式将字符串的一部分转换为double

[英]Convert part of string to double with regex

My application seem crash on "wrong format", I have this: 我的应用程序似乎崩溃“错误的格式”,我有这个:

Match m = Regex.Match(value, "[0-9]+[.[0-9]+]?");
double number = Convert.ToDouble(m.Value);
return number;

Point is to make string values like this: 114.6W, 120.6W. 114.6W, 120.6W.是这样的字符串值: 114.6W, 120.6W. into values I can sort. 我可以分类的价值观。 My function that I wrote is suppose to turn any string into a 9999.9999 double value, but it crash on Convert.ToDouble() . 我写的函数假设将任何字符串转换为9999.9999双精度值,但它在Convert.ToDouble()上崩溃。 Saying wrong input format? 说错输入格式?

The problem is with your regex: it should read 问题在于你的正则表达式:应该阅读

[0-9]+(\.[0-9]+)?

[.[0.9]+] (which I am surprised parses at all) is a character class looking for any character in the following set: a dot, an opening and closing bracket, 0 to 9, or a plus sign. [.[0.9]+] (我很惊讶解析)是一个字符类,用于查找以下集合中的任何字符:点,开始和结束括号,0到9或加号。

Maybe the . 也许吧. is not the decimal separator for the culture you are using. 不是您正在使用的文化的小数分隔符。 Try specifying InvariantCulture when parsing: 解析时尝试指定InvariantCulture

double number = Convert.ToDouble(m.Value, CultureInfo.InvariantCulture);

您必须用括号替换方括号

Match m = Regex.Match(value, @"[0-9]+(?:\.[0-9]+)?");

If it is guaranteed to always be a decimal number followed by a single letter, then: 如果保证始终是十进制数后跟一个字母,则:

var word = "120.6W";
var d = Decimal.Parse(word.Substring(0,word.Length-1));

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) ,但只有当后面跟着一个W (不会抓住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 或者,如果您的数据集只包含数字加上一个字母而前面或后面没有任何内容,请按@paul建议,只删除最后一个字符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM