Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract decimal Number from string in C# [duplicate]

Tags:

string

c#

regex

I am trying to extract numbers from my string using the following code:

var mat = Regex.Match(stringValue, @"\d+").Value;

But when stringValue contains a decimal like "($23.01)", It only extracts 23 instead of 23.01. How can I get the decimal value 23.01?

like image 829
Huma Ali Avatar asked Jun 14 '17 05:06

Huma Ali


2 Answers

Try to approach the problem this way. A decimal number has the following features:

  • start with one or more digits (\d+)
  • after that, there can be one or 0 dots (\.?)
  • if a dot is present, one or more digits should also follow (\d+)

Since the last two features are kind of related, we can put it in a group and add a ? quantifier: (\.\d+)?.

So now we have the whole regex: \d+(\.\d+)?

If you want to match decimal numbers like .01 (without the 0 at the front), you can just use | to mean "or" and add another case (\.\d+). Basically: (\d+(\.\d+)?)|(\.\d+)

like image 94
Sweeper Avatar answered Oct 04 '22 23:10

Sweeper


Have you tried this Example:

string inputStr =  "($23.01)";      
Console.WriteLine(Regex.Match(inputStr, @"\d+.+\d").Value);

Or else you can try this LinqSolution:

Console.WriteLine(String.Concat(inputStr.Where(x=> x=='.'||Char.IsDigit(x))));
like image 20
sujith karivelil Avatar answered Oct 04 '22 21:10

sujith karivelil