0

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?

Haseeb Khan
  • 930
  • 3
  • 19
  • 41

1 Answers1

1

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

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • I have another situation in which I need to extract string followed which sometimes contain a decimal number and sometimes not. I have two string like this MACD(C,26,12,9) SMA(C,26,12,9).1 when i use this regex (MACD)\([^()]*\)\.(?\d+) its only select one with decimal number but I want to select both. What I am doing wrong here? – Haseeb Khan Nov 04 '16 at 14:36
  • You need to be specific. If you need to specify exact context (match `.` after `MACD`, `SMA` (Forex terms, I know)), you need to use alternation: [`@"(?n)\b(MACD|SMA)\([^()]*\)\.(?\d+)"`](http://regexstorm.net/tester?p=%5cb%28MACD%7cSMA%29%5c%28%5b%5e%28%29%5d*%5c%29%5c.%28%3f%3cdecimal%3e%5cd%2b%29&i=MACD%28C%2c26%2c12%2c9%29.12+SMA%28C%2c26%2c12%2c9%29.1&o=n). – Wiktor Stribiżew Nov 04 '16 at 14:39
  • its only select SMA string but not MACD string. Do I need to use OR condition to select both? – Haseeb Khan Nov 04 '16 at 14:44
  • Your `MACD(C,26,12,9)` has no period. How come you want it to be matched? – Wiktor Stribiżew Nov 04 '16 at 14:46
  • that's what I mentioned that I wanted to select both sometime string have period and sometimes not – Haseeb Khan Nov 04 '16 at 15:16
  • period is optional – Haseeb Khan Nov 04 '16 at 15:18
  • Then use `\b(MACD|SMA)\([^()]*\)(\.(?\d+))?` – Wiktor Stribiżew Nov 04 '16 at 15:31