简体   繁体   中英

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 $() . ie expected result is

[2.1,3.2,23.2]

How can I achieve this?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM