当天的正则表达式流行测验:D

时间:2010-07-08 15:46:53

标签: ruby regex

如果我有这样的字符串..

 There                   is             a lot           of           white space.

我想删除Ruby正则表达式中所有不需要的空间。你如何识别空格并将其删除,以便所有单词之间至少还有一个空格?

到目前为止,我有:

gsub(/\s{2,}/, '')

但正如你所看到的那样,将几个单词折叠成彼此。

2 个答案:

答案 0 :(得分:11)

你很亲密。修剪左右两边的空白后,

str.strip.gsub(/\s{2,}/, ' ')

用一个空格替换任何多个空格的集合。当然,这假设您只处理实际空间。

答案 1 :(得分:2)

当我一直在编写Perl代码时,我曾经为我的字符串操作抓取正则表达式。然后,有一天我想制作一些搜索和解析字符串内容的代码,并编写了一个基准来比较一些正则表达式和基于标准字符串索引的搜索。基于索引的搜索打破了正则表达式。它并不复杂,但有时我们在处理简单问题时不需要复杂。

而不是立即获取正则表达式String.squeeze(' ')可以更快地压缩重复的空格。考虑基准的输出:

#!/usr/bin/env ruby

require 'benchmark'

asdf = 'There                   is             a lot           of           white space.'

asdf.squeeze(' ') # => "There is a lot of white space."
asdf.gsub(/  +/, ' ') # => "There is a lot of white space."
asdf.gsub(/ {2,}/, ' ') # => "There is a lot of white space."
asdf.gsub(/\s\s+/, ' ') # => "There is a lot of white space."
asdf.gsub(/\s{2,}/, ' ') # => "There is a lot of white space."

n = 500000
Benchmark.bm(8) do |x|
  x.report('squeeze:') { n.times{ asdf.squeeze(' ') } }
  x.report('gsub1:') { n.times{ asdf.gsub(/  +/, ' ') } }
  x.report('gsub2:') { n.times{ asdf.gsub(/ {2,}/, ' ') } }
  x.report('gsub3:') { n.times{ asdf.gsub(/\s\s+/, ' ') } }
  x.report('gsub4:') { n.times{ asdf.gsub(/\s{2,}/, ' ') } }
end

puts
puts "long strings"
n     = 1000
str_x = 1000
Benchmark.bm(8) do |x|
  x.report('squeeze:') { n.times{(asdf * str_x).squeeze(' ') }}
  x.report('gsub1:') { n.times{(asdf * str_x).gsub(/  +/, ' ') }}
  x.report('gsub2:') { n.times{(asdf * str_x).gsub(/ {2,}/, ' ') }}
  x.report('gsub3:') { n.times{(asdf * str_x).gsub(/\s\s+/, ' ') }}
  x.report('gsub4:') { n.times{(asdf * str_x).gsub(/\s{2,}/, ' ') }}
end
# >>               user     system      total        real
# >> squeeze:  1.050000   0.000000   1.050000 (  1.055833)
# >> gsub1:    3.700000   0.020000   3.720000 (  3.731957)
# >> gsub2:    3.960000   0.010000   3.970000 (  3.980328)
# >> gsub3:    4.520000   0.020000   4.540000 (  4.549919)
# >> gsub4:    4.840000   0.010000   4.850000 (  4.860474)
# >> 
# >> long strings
# >>               user     system      total        real
# >> squeeze:  0.310000   0.180000   0.490000 (  0.485224)
# >> gsub1:    3.420000   0.130000   3.550000 (  3.554505)
# >> gsub2:    3.850000   0.120000   3.970000 (  3.974213)
# >> gsub3:    4.880000   0.130000   5.010000 (  5.015750)
# >> gsub4:    5.310000   0.150000   5.460000 (  5.461797)

测试基于让squeeze(' ')gsub()去除重复的空格。正如我所料,挤压('')打破了正则表达式。使用空格字符的正则表达式比使用\s的等效模式更快。

当然正则表达式更灵活,但考虑是否需要正则表达式会对代码的处理速度产生很大影响。