ruby - 我需要一个正则表达式来捕获字符串中的数字

标签 ruby regex

我无权访问代码,这是通过一个接口(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/

相关文章:

regex - 美国电话号码验证

正则表达式匹配字符串中的两个单词

regex - 在 Powershell 中插入数字替换

ruby - 在 Ruby 1.8.7 中使用标题大小写

ruby - 与 Webdriver 相比,Watir-Webdriver 和 Capybara 是否存在性能问题?

ruby - .irb_history 和 .irb-history 的区别

带有日志头的正则表达式模式

R - 反转 gsub : keep only matches with gsub argument

ruby - 无法让 Sinatra Flash Gem 工作

ruby-on-rails - Rails ActionController 未知格式