Extract number from string in Ruby

后端 未结 7 2066
既然无缘
既然无缘 2020-12-02 10:59

I\'m using this code:

s = line.match( /ABCD(\\d{4})/ ).values_at( 1 )[0] 

To extract numbers from strings like:

ABCD1234
AB         


        
相关标签:
7条回答
  • 2020-12-02 11:27
    a.map {|x| x[/\d+/]}
    
    0 讨论(0)
  • 2020-12-02 11:34

    There are many Ruby ways as per http://www.ruby-forum.com/topic/125709

    1. line.scan(/\d/).join('')
    2. line.gsub(/[^0-9]/, '')
    3. line.gsub(/[^\d]/, '')
    4. line.tr("^0-9", '')
    5. line.delete("^0-9")
    6. line.split(/[^\d]/).join
    7. line.gsub(/\D/, '')

    Try each on you console.

    Also check the benchmark report in that post.

    0 讨论(0)
  • 2020-12-02 11:46

    The simplest and fastest way is to just get all integers out of the string.

    str = 'abc123def456'
    
    str.delete("^0-9")
    => "123456"
    

    Comparing benchmarks on a long string with some of the other solutions provided here, we can see this is orders of magnitude faster:

    require 'benchmark'
    
    @string = [*'a'..'z'].concat([*1..10_000].map(&:to_s)).shuffle.join
    
    Benchmark.bm(10) do |x|
      x.report(:each_char) do
        @string.each_char{ |c| @string.delete!(c) if c.ord<48 or c.ord>57 }
      end
      x.report(:match) do |x|
        /\d+/.match(@string).to_s
      end
      x.report(:map) do |x|
        @string.split.map {|x| x[/\d+/]}
      end
      x.report(:gsub) do |x|
        @string.gsub(/\D/, '')
      end
      x.report(:delete) do
        @string.delete("^0-9")
      end
    end
    
                 user     system      total        real
    each_char    0.020000   0.020000   0.040000 (  0.037325)
    match        0.000000   0.000000   0.000000 (  0.001379)
    map          0.000000   0.000000   0.000000 (  0.001414)
    gsub         0.000000   0.000000   0.000000 (  0.000582)
    delete       0.000000   0.000000   0.000000 (  0.000060)
    
    0 讨论(0)
  • 2020-12-02 11:46

    Another solution may be to write:

    myString = "sami103"
    myString.each_char{ |c| myString.delete!(c) if c.ord<48 or c.ord>57 } #In this case, we are deleting all characters that do not represent numbers.
    

    Now, if you type

    myNumber = myString.to_i #or myString.to_f
    

    This should return a

    0 讨论(0)
  • 2020-12-02 11:48
    your_input = "abc1cd2"
    your_input.split(//).map {|x| x[/\d+/]}.compact.join("").to_i
    

    This should work.

    0 讨论(0)
  • 2020-12-02 11:49

    there is even simpler solution

    line.scan(/\d+/).first
    
    0 讨论(0)
提交回复
热议问题