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

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

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

我如何从ruby中的这个字符串中检索数字?

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

更新:我相信语法是/(\\ +)/。匹配(your_string)

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

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

 \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