Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a number from a regex expression in c#?

Tags:

c#

regex

I have a specific pattern with the following format

string exp = "$(2.1)+$(3.2)-tan($(23.2)) * 0.5";

Using this code I get the following result

var doubleArray = Regex
  .Split(str, @"[^0-9\.]+")
  .Where(c => c != "." && c.Trim() != "")
  .ToList();

//result
[2.1,3.2,23.2,0.5]

I want to split number from $() . i.e. expected result is

[2.1,3.2,23.2]

How can I achieve this?

like image 984
Nithin Mohan Avatar asked Feb 05 '23 04:02

Nithin Mohan


2 Answers

I suggest extracting Matches instead of Split:

string exp = "$(2.1)+$(3.2)-tan($(23.2)) * 0.5";

var doubleArray = Regex
  .Matches(exp, @"\$\((?<item>[0-9.]+)\)")
  .OfType<Match>()
  .Select(match => match.Groups["item"].Value)
  .ToList();

Console.WriteLine(string.Join("; ", doubleArray));

Outcome:

2.1; 3.2; 23.2
like image 200
Dmitry Bychenko Avatar answered Feb 08 '23 15:02

Dmitry Bychenko


Similar to Dmitry's answer but instead of using a sub group using a zero width look behind:

string str = "$(2.1)+$(3.2)-tan($(23.2)) * 0.5";

var doubleArray =
    Regex
        .Matches(str, @"(?<=\$\()[0-9\.]+")
        .Cast<Match>()
        .Select(m => Convert.ToDouble(m.Value))
        .ToList();

foreach (var d in doubleArray)
{
    Console.WriteLine(d);
}
like image 39
Martin Brown Avatar answered Feb 08 '23 15:02

Martin Brown