Nithin Mohan
Nithin Mohan

Reputation: 770

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

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?

Upvotes: 9

Views: 140

Answers (2)

Martin Brown
Martin Brown

Reputation: 25310

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);
}

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186678

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

Upvotes: 10

Related Questions