Haseeb Khan Haseeb Khan - 1 month ago 7
C# Question

C# Extract Decimal number with out period

I need to extract a decimal number from string. Currently I am using this regex to find a decimal number but it need a proper decimal value.

var value = Regex.Match(formula, @"(?n)\d+(\.(?<decimal>\d+))?");
return value.Groups["decimal"].Success ? int.Parse(value.Groups["decimal"].Value) : 0;


if I write
2.1
it gives me
1
but when write
.1
it doesn't evaluate that string.

I need to extract a decimal number from these string with one regex

2.1 = 1
.5 = 5
SMA(21).6 = 6


How to do it?

Answer

It seems you just want to extract 1 or more digits after a dot. You may use a simple \.(\d+) regex that matches a literal dot and then matches and captures 1 or more digits into Group 1.

Use

var m = Regex.Match(formula, @"\.(\d+)");
var res = string.Empty;
if (m.Success)
{ 
    res = m.Groups[1].Value;
}

See the regex demo

enter image description here