Haseeb Khan Haseeb Khan - 1 year ago 91
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
it gives me
but when write
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 Source

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.


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download