正则表达式获取字符串中的十进制值 [英] Regex to get decimal value in string
问题描述
因为我是 C# 开发人员,所以我也接受 C# 的答案.
As I am a C# developer, I would accept C# answers as well.
假设我有这个字符串:R 560.00"
Lets say I have this string: "R 560.00"
有一个 Alpha 字符和一个带十进制值的空格.
There is a Alpha character and a space with the decimal value.
我们也可以在字符串上加上引号.
We can also have the quotations on the string.
但我想要的是只获取字符串中的 Decimal 值.应删除所有其他字符.
But what I want, is to only get the Decimal value in the string. All the other characters should be removed.
注意:String.Replace 并没有达到我想要的效果,这就是我转向 Regex 的原因.
NOTE: The String.Replace does not work as far as I want, that is why I turn to Regex.
这是我尝试过的:fields(amountIdx) 将包含 R560.00
This is what I have tried: fields(amountIdx) will contain the 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})?$")
但金额反映为 R 560.00.它不会删除其他字符.我怎样才能做到这一点?
But the amount reflects back as R 560.00. It does not remove the other characters. How can I accomplish this?
推荐答案
你可以简单地使用
Regex.Replace("R500.12", "[^-?\d+\.]", ""))
例如:MsgBox(Regex.Replace("R500.12", "[^-?\d+\.]", ""))
它将返回 500.12
It will return 500.12
这篇关于正则表达式获取字符串中的十进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!