我正在使用此代码:
s = line.match( /ABCD(\d{4})/ ).values_at( 1 )[0] 
从字符串中提取数字,如:
ABCD1234
ABCD1235
ABCD1236
等等
它有效,但我想知道在Ruby中我还有什么其他选择吗?
我的代码:
ids = [] 
someBigString.lines.each {|line|
   ids << line.match( /ABCD(\d{4})/ ).values_at( 1 )[0] 
}
Ami*_*tel 155
根据http://www.ruby-forum.com/topic/125709,有很多Ruby方法
line.scan(/\d/).join('')line.gsub(/[^0-9]/, '')line.gsub(/[^\d]/, '')line.tr("^0-9", '')line.delete("^0-9")line.split(/[^\d]/).joinline.gsub(/\D/, '')在你的控制台上试试.
同时查看该帖子中的基准报告.
gle*_*ald 32
a.map {|x| x[/\d+/]}
最简单和最快的方法是从字符串中取出所有整数。
str = 'abc123def456'
str.delete("^0-9")
=> "123456"
将长字符串上的基准测试与此处提供的其他一些解决方案进行比较,我们可以看到接近 2nd 的delete速度最快tr。
require 'benchmark'
n = 2 
string = [*'a'..'z'].concat([*1..1_000_000].map(&:to_s)).shuffle.join
Benchmark.bmbm do |x|
  x.report('scan') do
    n.times {string.scan(/\d/).join}
  end
  x.report('gsub') do
    n.times {string.gsub(/[^\d]/,"")}
  end
  x.report('gsub2') do
    n.times {string.gsub(/\D/, '')}
  end
  x.report('tr') do
    n.times {string.tr("^0-9","")}
  end
  x.report('delete') do
    n.times {string.delete('^0-9')}
  end
  x.report('split') do
    n.times {string.split(/[^\d]/).join}
  end
end
Rehearsal ------------------------------------------
scan     3.509973   0.187274   3.697247 (  3.717773)
gsub     0.229568   0.002790   0.232358 (  0.233961)
gsub2    0.307728   0.013435   0.321163 (  0.390262)
tr       0.021395   0.000223   0.021618 (  0.022297)
delete   0.021290   0.002280   0.023570 (  0.024365)
split    0.284935   0.010274   0.295209 (  0.299865)
--------------------------------- total: 4.591165sec
             user     system      total        real
scan     3.146615   0.126009   3.272624 (  3.281860)
gsub     0.211263   0.001515   0.212778 (  0.213170)
gsub2    0.208482   0.000424   0.208906 (  0.209339)
tr       0.015228   0.000086   0.015314 (  0.015387)
delete   0.015786   0.000128   0.015914 (  0.016050)
split    0.205096   0.002736   0.207832 (  0.208380)
| 归档时间: | 
 | 
| 查看次数: | 57577 次 | 
| 最近记录: |