【发布时间】:2010-10-16 04:51:45
【问题描述】:
我有一个字符串“搜索结果:找到 16143 个结果”,我需要从中检索 16143。
我正在使用 ruby 进行编码,我知道使用 RegEx 获取它会很干净(与基于分隔符拆分字符串相反)
如何在 ruby 中从这个字符串中检索数字?
【问题讨论】:
-
您确定该数字为非负数、不包含任何非数字数字且不会采用指数表示法吗?
我有一个字符串“搜索结果:找到 16143 个结果”,我需要从中检索 16143。
我正在使用 ruby 进行编码,我知道使用 RegEx 获取它会很干净(与基于分隔符拆分字符串相反)
如何在 ruby 中从这个字符串中检索数字?
【问题讨论】:
> foo = "Search result:16143 Results found"
=> "Search result:16143 Results found"
> foo[/\d+/].to_i
=> 16143
【讨论】:
我不确定 Ruby 中的语法,但正则表达式是“(\d+)”,表示大小为 1 或更大的数字字符串。你可以在这里试试:http://www.rubular.com/
更新: 我相信语法是 /(\d+)/.match(your_string)
【讨论】:
这个正则表达式应该这样做:
\d+
【讨论】:
对于非正则表达式方法:
irb(main):001:0> foo = "Search result:16143 Results found"
=> "Search result:16143 Results found"
irb(main):002:0> foo[foo.rindex(':')+1..foo.rindex(' Results')-1]
=> "16143"
【讨论】:
# check that the string you have matches a regular expression
if foo =~ /Search result:(\d+) Results found/
# the first parenthesized term is put in $1
num_str = $1
puts "I found #{num_str}!"
# if you want to use the match as an integer, remember to use #to_i first
puts "One more would be #{num_str.to_i + 1}!"
end
【讨论】:
> foo = "Search result:16143 Results found"
=> "Search result:16143 Results found"
> foo.scan(/\d/).to_i
=> 16143
【讨论】: