我无权访问代码,这是通过一个接口(interface)实现的,该接口(interface)只允许我编辑解析用户响应的正则表达式。我需要在用户发短信后提取权重,他们发的短信如下:
wt 172.5
172.5 lbs
180
wt. 173.22
172,5
我需要将权重捕获为浮点字段,但我想将其限制为最多 1 位小数。我尝试使用 /(?<val>[\d+((\.|,)\d\d?)?]/
但它只保存字段中的第一个数字“1”
最佳答案
有时看似最简单的事情其实并非如此。我建议使用这个正则表达式:
r = /(?<=\A|\s)\d+(?:[.,]\d)?(?=\d|\s|\z)/
我们也可以使用扩展或自由间距模式定义正则表达式(通过在最后的/后添加修饰符
),它允许我们包含文档:x
)
r = /
(?<=\A|\s) # match beginning of string or space in a positive lookbehind
\d+ # match one or more digits
(?:[.,]\d)? # optionally (? after non-capture group) match a . or , then a digit
(?=\d|\s|\z) # match a digit, space or the end of the string in a positive lookahead
/x
"wt 172.5"[r] #=> "172.5"
"172.5 lbs"[r] #=> "172.5"
"180"[r] #=> "180"
"wt. 173.22"[r] #=> "173.2"
"172,5"[r] #=> "172,5"
"A1 143.66"[r] #=> "143.6"
"A1 1.3.4 43.6"[r] #=> "43.6"
关于ruby - 我需要一个正则表达式来捕获字符串中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35511705/