[英]How to split a number from a regex expression in c#?
我有以下格式的特定模式
string exp = "$(2.1)+$(3.2)-tan($(23.2)) * 0.5";
使用此代碼我得到以下結果
var doubleArray = Regex
.Split(str, @"[^0-9\.]+")
.Where(c => c != "." && c.Trim() != "")
.ToList();
//result
[2.1,3.2,23.2,0.5]
我想從$()
拆分數字。 即預期的結果是
[2.1,3.2,23.2]
我怎樣才能做到這一點?
我建議提取Matches
而不是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));
結果:
2.1; 3.2; 23.2
類似於 Dmitry 的答案,但不是使用使用零寬度查看后面的子組:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.