2010-07-08 60 views
3

如果我有像這樣的字符串..正則表達式突擊測驗:d

There     is    a lot   of   white space. 

我想刪除Ruby的正則表達式所有不需要的空間..如何識別空白和刪除那麼所有單詞之間至少還會有一個空格?

到目前爲止,我有:

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

但正如你可以看到,塌陷幾個詞相互轉化。

回答

11

你很近。修剪完左邊和右邊的空白後,

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

用一個空格替換多個空格的任何集合。當然,這是假設你只處理實際空間。

+0

哦,夥計! :D太近了! – Trip 2010-07-08 15:50:23

+0

這個答案有效。它明顯優於簡單的'.gsub(/ \ s + /,'')'。 – 2010-07-08 15:51:28

+0

@Steven Xu - 儘管用單個空間替換單個空間也很有趣! – Matchu 2010-07-08 15:53:13

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的等效模式更快。

當然,正則表達式更加靈活,但考慮是否需要使用正則表達式會對代碼的處理速度產生很大的影響。