vb.net 正则表达式获取字符串中的十进制值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20467730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex to get decimal value in string
提问by Fred
As I am a C# developer, I would accept C# answers as well.
由于我是 C# 开发人员,因此我也接受 C# 答案。
Lets say I have this string: "R 560.00"
假设我有这个字符串:“R 560.00”
There is a Alpha character and a space with the decimal value.
有一个 Alpha 字符和一个带十进制值的空格。
We can also have the quotations on the string.
我们也可以在字符串上使用引号。
But what I want, is to only get the Decimal value in the string. All the other characters should be removed.
但我想要的是只获取字符串中的 Decimal 值。应删除所有其他字符。
NOTE: The String.Replace does not work as far as I want, that is why I turn to Regex.
注意: String.Replace 不能按我想要的那样工作,这就是我转向 Regex 的原因。
This is what I have tried: fields(amountIdx) will contain the R560.00
这是我尝试过的: fields(amountIdx) 将包含 R560.00
Dim regex As New Regex("^[0-9]+(\.[0-9]{1,2})?$", RegexOptions.IgnoreCase)
Dim amount As String = regex.Replace(fields(amountIdx), "^[0-9]+(\.[0-9]{1,2})?$")
But the amount reflects back as R 560.00. It does not remove the other characters. How can I accomplish this?
但金额反映为 R 560.00。它不会删除其他字符。我怎样才能做到这一点?
回答by Vignesh Kumar A
You can simply use
你可以简单地使用
Regex.Replace("R500.12", "[^-?\d+\.]", ""))
Eg: MsgBox(Regex.Replace("R500.12", "[^-?\d+\.]", ""))
例如: MsgBox(Regex.Replace("R500.12", "[^-?\d+\.]", ""))
It will return 500.12
它将返回 500.12
回答by Lingasamy Sakthivel
Try this
尝试这个
var resultArray = Regex.Split(input_string, @"[^0-9\.]+")
.Where(c => c != "." && c.Trim() != "");
Where (c=>...) is the lambda for dealing with each element of the array and c is an array element
其中 (c=>...) 是用于处理数组每个元素的 lambda,c 是一个数组元素
回答by lc.
Here's a LINQ hack to take the first decimal-y positive number in a string, where "decimal-y" is defined by a sequence of digits and dots:
这是一个 LINQ hack,用于获取字符串中的第一个十进制 y 正数,其中“十进制 y”由一系列数字和点定义:
string s = "R 560.00";
string decimalyNumber = new String(s.SkipWhile(c => !Char.IsDigit(c) || c != '.')
.TakeWhile(c => Char.IsDigit(c) || c == '.').ToArray());
It works by skipping over characters until it finds a digit/dot, then taking everything in the contiguous sequence of digits and dots. I would imagine the performance would not be that hot, but unless you've got millions of these to do in a short time...
它的工作原理是跳过字符直到找到一个数字/点,然后在数字和点的连续序列中获取所有内容。我想表演不会那么火爆,但除非你在短时间内有数百万个这样的事情要做......
Or, you can use Regex and simply match [0-9]*(?:\.[0-9]+)?, which is zero or more digits optionally followed by a dot and one or more digits (non-captured).
或者,您可以使用 Regex 并简单地 match [0-9]*(?:\.[0-9]+)?,它是零个或多个数字,可选地后跟一个点和一个或多个数字(未捕获)。

