简体   繁体   中英

How to get all digits from string regexp ruby

如何使用红宝石中的regexp获取句子字符串中的所有数字,如“Lorem 123 ipsum 456 879”=>“123456879”?

只需替换其他一切。

result = subject.gsub(/[^\d]/, '')

没有正则表达式:

"Lorem 123 ipsum 456 879".delete('^0-9') #=>"123456879"

参考这个

result = subject.gsub(/\D/, '')  
"Lorem 123 ipsum 456 879".scan(/\d+/).join # => "123456879"

The version from @steenslag is the fastest, thx!

require 'benchmark'

class ExtractInt
  def self.v1(string)
    string.gsub(/[^\d]/, '')
  end

  def self.v2(string)
    string.gsub(/\D/, '') 
  end


  def self.v3(string)
    string.delete('^0-9')
  end

  def self.run(m, arg)
    10000.times do 
      self.send(m, arg)
    end
  end
end


Benchmark.bmbm do |x|
  x.report('v1') { ExtractInt.run(:v1, 'AAAA4000') }
  x.report('v2') { ExtractInt.run(:v2, 'AAAA4000') }
  x.report('v3') { ExtractInt.run(:v3, 'AAAA4000') }
end


# Rehearsal --------------------------------------
# v1   0.040000   0.000000   0.040000 (  0.041564)
# v2   0.040000   0.000000   0.040000 (  0.042386)
# v3   0.010000   0.000000   0.010000 (  0.011604)
# ----------------------------- total: 0.090000sec

#          user     system      total        real
# v1   0.040000   0.000000   0.040000 (  0.042176)
# v2   0.040000   0.000000   0.040000 (  0.043753)
# v3   0.010000   0.000000   0.010000 (  0.012960)

我一直以为使用括号更容易阅读

"nwa240".chars.select {|s| s =~ /[0-9]/}

Some correct answers already given, which probably includes what you want to use. A slightly more low-level way:

"Lorem 123 ipsum 456 879".chars.select {|c| c =~ /\d/}.join

tr() is pretty comparable to delete performance wise!

  ...
  def self.v3(string)
    string.delete('^0-9')
  end

  def self.v4(string)
    string.tr('^0-9', '')
  end

  def self.run(m, arg)
    10000.times do
      self.send(m, arg)
    end
  end
  ...

Console:

v3   0.010000   0.000000   0.010000 (  0.005608)
v4   0.010000   0.000000   0.010000 (  0.006141)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM