Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to get decimal value in string

Tags:

c#

regex

vb.net

As I am a C# developer, I would accept C# answers as well.

Lets say I have this string: "R 560.00"

There is a Alpha character and a space with the decimal value.

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.

NOTE: The String.Replace does not work as far as I want, that is why I turn to Regex.

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})?$")

But the amount reflects back as R 560.00. It does not remove the other characters. How can I accomplish this?

like image 767
Fred Avatar asked Dec 12 '25 09:12

Fred


2 Answers

You can simply use

Regex.Replace("R500.12", "[^-?\d+\.]", ""))

Eg: MsgBox(Regex.Replace("R500.12", "[^-?\d+\.]", ""))

It will return 500.12

like image 150
Vignesh Kumar A Avatar answered Dec 13 '25 22:12

Vignesh Kumar A


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

like image 39
Linga Avatar answered Dec 13 '25 22:12

Linga