从字符串中提取双精度/十进制数 [英] Extracting double/decimal number from string

查看:101
本文介绍了从字符串中提取双精度/十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从以下字符串中提取33345.002:

"ABC(MAX)(33345.002)"

如何在C#中执行此操作?
我尝试在SQL中处理它,但也选择了(MAX),所以现在我要尝试c#.
谢谢

I need to extract the 33345.002 from the following string:

"ABC(MAX)(33345.002)"

How can I perform this in c#?
I tried handling it in SQL but was picking up the (MAX) too so now I''m gonna try c#.
Thanks

推荐答案

我会去寻找正则表达式.

您可以在此处找到一些信息.

还有一个工具 Expresso ,该工具对于构建表达式并针对尽可能多的条目进行测试最有用如您所愿/
.
看正则表达式值得额外的学习时间;您会发现它们在许多情况下都非常方便.

对于您的问题,它将是(已更新为可变长度和任何字母数字字符):

^(?:[\w]+\([\w]+\))\((?<NamedValue>[\d]+(?:\.[\d]+)?)\)
I would go for a regular expression.

You can find some informations here.

And there is a tool, Expresso, most useful to build your expressions and test them against as much entries as you want/need to.

Having a look at regular expressions is worth the additional learning time ; you will find they can be handy in many situations.

For your question, it would be (updated for variable lengths and any alphanumeric character) :

^(?:[\w]+\([\w]+\))\((?<NamedValue>[\d]+(?:\.[\d]+)?)\)




该链描述为:
行首-一个或多个字母,然后用括号括起来的一个或多个字母,然后是用括号括起来的命名捕获组.此命名的捕获组由一个或多个数字组成,后跟一个点或一个或多个数字,而不是一个点-行尾

您可以在NamedValue中获取双精度字符串的字符串表示形式.
您可以使用hzawary告诉您的方法将其转换为两倍,但只传递您得到的NamedValue.最好使用Double.TryParse()处理有问题的条目.



Which describes the chain as :
Begin of line - One or more letters, followed by one or more letters enclosed in parenthesis, followed by a named capture group enclosed in parenthesis. This named capture group is composed of one or more digits, followed or not by a point and one or more digits - End of line

You can obtain the string representation of your double in NamedValue.

You can convert it to double by using the method hzawary told you, but passing only the NamedValue you got. It can be great to use Double.TryParse() to handle problematic entries.

double d;
bool ok = double.TryParse(yourMatch.Group["NamedValue"].Value, out d);



希望对您有所帮助.



Hope this helps.


这是基于Split:
的更正解决方案
Here is the corrected solution based on Split:

static double ExtractFrom(string value) {
   string[] parts = value.Split(new char[] {'(', ')'}, System.StringSplitOptions.RemoveEmptyEntries);
   string numeric = parts[parts.Length-1]; //sic!
   return double.Parse(numeric);
}



另请参见Phil的基于Regex的解决方案.可以的,我没有测试.

—SA



See also the Regex-based solution by Phil. It can be correct, I did not test it.

—SA


这篇关于从字符串中提取双精度/十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆