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?
Try to approach the problem this way. A decimal number has the following features:
\d+)\.?)\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+)
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))));
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With