删除Ruby字符串中除字母和数字之外的所有字符

时间:2011-01-10 19:47:42

标签: ruby string

我在表单中有一个字符串输入字段。我在params hash中得到了这个值。如何从该字符串中删除除字母和数字之外的所有字符。

3 个答案:

答案 0 :(得分:56)

只是为了提醒人们好'ol 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[\]^_`abcdefghijklmnopqrstuvwxyz0123456789
>> ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
>> ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
>> ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz0123456789
>> ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz0123456789
>> ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
>> ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
>>              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的要求。

答案 1 :(得分:21)

没有正则表达式:

garbage = 'ab_c<>?AB C!@#123'
puts garbage.delete("^a-zA-Z0-9") #=> abcABC123

其中'^'否定了它之后的所有内容。

答案 2 :(得分:7)

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

...根据评论更新......