【问题标题】:Retrieve number from the string pattern using regular expression使用正则表达式从字符串模式中检索数字
【发布时间】:2010-10-16 04:51:45
【问题描述】:

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

我正在使用 ruby​​ 进行编码,我知道使用 RegEx 获取它会很干净(与基于分隔符拆分字符串相反)

如何在 ruby​​ 中从这个字符串中检索数字?

【问题讨论】:

  • 您确定该数字为非负数、不包含任何非数字数字且不会采用指数表示法吗?

标签: ruby regex


【解决方案1】:
> foo = "Search result:16143 Results found"
=> "Search result:16143 Results found"
> foo[/\d+/].to_i
=> 16143

【讨论】:

  • 这是从基于正则表达式模式的字符串中提取的首选方法。
【解决方案2】:

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

更新: 我相信语法是 /(\d+)/.match(your_string)

【讨论】:

  • 请注意,将 \d+ 放在括号中实际上捕获了值,而不是仅仅返回与匹配相关的 true 或 false
  • 不要忘记将其转换为整数(Integer(foo) 和 foo.to_i 都不是完美的,但如果您知道它是完美的,我会建议 to_i一个数字)。
【解决方案3】:

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

\d+

【讨论】:

    【解决方案4】:

    对于非正则表达式方法:

    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"
    

    【讨论】:

      【解决方案5】:
       # 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
      

      【讨论】:

        【解决方案6】:
        > foo = "Search result:16143 Results found"
        => "Search result:16143 Results found"
        > foo.scan(/\d/).to_i
        => 16143
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-03-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-11-28
          • 1970-01-01
          相关资源
          最近更新 更多