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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With