使用正则表达式从字符串模式中检索数字

时间:2009-03-29 05:51:46

标签: ruby regex

我有一个字符串“搜索结果:找到16143个结果”,我需要从中检索16143。

我正在使用ruby进行编码,我知道使用RegEx进行编码会很干净(反对根据分隔符拆分字符串)

如何从ruby中的此字符串中检索数字?

6 个答案:

答案 0 :(得分:11)

> foo = "Search result:16143 Results found"
=> "Search result:16143 Results found"
> foo[/\d+/].to_i
=> 16143

答案 1 :(得分:2)

我不确定Ruby中的语法,但正则表达式将是“(\ d +)”,表示大小为1或更大的数字字符串。你可以在这里试试:http://www.rubular.com/

<强>更新 我相信语法是/(\ d +)/。match(your_string)

答案 2 :(得分:1)

这个正则表达式应该这样做:

\d+

答案 3 :(得分:1)

对于非正则表达式方法:

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"

答案 4 :(得分:1)

 # 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

答案 5 :(得分:0)

> foo = "Search result:16143 Results found"
=> "Search result:16143 Results found"
> foo.scan(/\d/).to_i
=> 16143