Extract decimal Number from string in C#
17,238
Solution 1
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+)
Solution 2
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))));
Author by
Huma Ali
Updated on July 17, 2022Comments
-
Huma Ali almost 2 years
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 thedecimal
value 23.01? -
xunatai almost 7 years
10.
or.01
aren't valid decimal numbers? -
Sweeper almost 7 years@xunatai No I don't consider them as decimal numbers
-
Sweeper almost 7 years@xunatai
10.
will just match10
anyway. And you just need to do\d*
instead of\d+
at the start to match.01
-
Sweeper almost 7 years@xunatai Oops! That was my quick thinking.
(\d+(\.\d+)?)|(\.\d+)
should work. -
Huma Ali almost 7 yearswhen string contains "($23)", This will fail
-
sujith karivelil almost 7 years@HumaAli:
Regex
will fail with that input you can try the Linq solution then -
Huma Ali almost 7 years@Sweeper will it work if string contains "($23)" and no decimal value?
-
Sweeper almost 7 years@HumaAli it will. Why not try it for yourself?
-
Huma Ali almost 7 years@Sweeper Just did. It works :)
-
Rob Sedgwick over 5 yearsjust add a question mark at the end: \d+.+\d?