2011-01-10 95 views

回答

52

只是提醒良好的人「醇tr

asdf.tr('^A-Za-z0-9', '') 

這是找到字符範圍的補充和轉換的字符'。

我很好奇,一個\W字符類是否使用快於範圍和gsubtr

require 'benchmark' 

asdf = [('A'..'z').to_a, ('0'..'9').to_a].join 

puts asdf 
puts asdf.tr( '^A-Za-z0-9', '') 
puts asdf.gsub(/[\W_]+/,  '') 
puts asdf.gsub(/\W+/,   '') 
puts asdf.gsub(/\W/,   '') 
puts asdf.gsub(/[^A-Za-z0-9]+/, '') 
puts asdf.scan(/[a-z\d]/i).join 

n = 100_000 
Benchmark.bm(7) do |x| 
    x.report("tr:") { n.times do; asdf.tr('^A-Za-z0-9', '');  end } 
    x.report("gsub1:") { n.times do; asdf.gsub(/[\W_]+/, '');  end } 
    x.report("gsub2:") { n.times do; asdf.gsub(/\W+/, '');   end } 
    x.report("gsub3:") { n.times do; asdf.gsub(/\W/, '');   end } 
    x.report("gsub4:") { n.times do; asdf.gsub(/[^A-Za-z0-9]+/, ''); end } 
    x.report("scan:") { n.times do; asdf.scan(/[a-z\d]/i).join;  end } 
end 

>> ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz
>> ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
>> ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
>> ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz
>> ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz
>> ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
>> ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
>>    user  system  total  real 
>> tr:  0.560000 0.000000 0.560000 ( 0.557883) 
>> gsub1: 0.510000 0.000000 0.510000 ( 0.513244) 
>> gsub2: 0.820000 0.000000 0.820000 ( 0.823816) 
>> gsub3: 0.960000 0.000000 0.960000 ( 0.955848) 
>> gsub4: 0.900000 0.000000 0.900000 ( 0.902166) 
>> scan: 5.630000 0.010000 5.640000 ( 5.630990) 

你可以看到一對夫婦的模式都沒有捕捉「_」,這是部分\w,結果不符合OP的要求。

7
=> '^/how/now#(Brown) Cow'.gsub /\W/, '' # or /[\W_]/ 
=> "hownowBrownCow" 

...基於評論更新中...

+0

HNBC的+1。 :) – 2011-01-10 19:54:19

+1

不刪除下劃線,這可能是一件好事。 – steenslag 2011-01-10 20:36:06

+2

或者您可以使用`.gsub/\ W /,''`,因爲\ W匹配任何非單詞字符(而\ w匹配單詞字符)。 – 2011-01-10 20:42:43

20

沒有一個正則表達式:

garbage = 'ab_c<>?AB [email protected]#123' 
puts garbage.delete("^a-zA-Z0-9") #=> abcABC123 

其中 '^' 後,它否定了一切。

相關問題