【发布时间】:2022-01-08 05:45:50
【问题描述】:
我正在使用正则表达式从包含范围的字符串中提取数字。范围可以是"less than x"、"greater than x" 或"between x and y":
"10 - 22"
"< 0,5"
"3.50000 - 11.0"
"< 120000"
"> 12"
下面是相关代码sn-p。对于"less than x" 和"greater than x",我使用正则表达式(\d*,\d*)?(\d*) 来捕获整数/小数。
Low = r.Descr.Contains('>')
? new Quantity {
Value = Convert.ToDecimal(Regex.Match(r.Descr, @"(\d*,\d*)?(\d*)").Value)
}
: r.Descr.Contains('-')
? new Quantity {
Value = Convert.ToDecimal(Regex.Match(r.Descr, @"").Value)
}
: null,
High = r.Descr.Contains('<')
? new Quantity {
Value = Convert.ToDecimal(Regex.Match(r.Descr, @"(\d*,\d*)?(\d*)").Value)
}
: r.Descr.Contains('-')
? new Quantity {
Value = Convert.ToDecimal(Regex.Match(r.Descr, @"").Value)
}
: null,
在"between x and y" 的情况下,我在构建一个提取相关数字的正则表达式时遇到了困难。有没有办法对这三种模式使用正则表达式?
【问题讨论】:
-
3,50000 - 11,0 是什么意思
-
是
var m = Regex.Match(text, @"(\d+(?:,\d+)?)\s*-\s*(\d+(?:,\d+)*)");,那么你就可以得到m.Groups[1].Value和m.Groups[2].Value的号码。 -
@GoldenLion 介于 3.5 和 11.0 之间。
-
包含部分检查字符 ,但模式
(\d*,\d*)?(\d*)也可以匹配空字符串或仅匹配逗号。使用\d+(?:,\d+)?,您将匹配至少一个数字。 -
上面需要编辑的数据也反映了3.5 - 11.0