2011-01-11 29 views
26

正規表現を使い慣れていないので、これを行う方法がわかりません。これを達成するための適切な方法を見つけることができないようですが、文字列(すべてのタブと改行が含まれています)Rubyはすべての空白を1つの空白に減らします

1/2 cup 




      onion   
      (chopped) 

すべての空白を削除して各インスタンスを1つのスペースで置き換えるにはどうすればよいですか?

str.squeeze([other_str]*) → new_str 
Builds a set of characters from the other_str parameter(s) using the procedure described for String#count. Returns a new string where runs of the same character that occur in this set are replaced by a single character. If no arguments are given, all runs of identical characters are replaced by a single character. 

    "yellow moon".squeeze     #=> "yelow mon" 
    " now is the".squeeze(" ")   #=> " now is the" 
    "putters shoot balls".squeeze("m-z") #=> "puters shot balls" 

答えて

53

これは、あなたが空白文字と同じのクラス全体を治療して空白の任意の組み合わせのランを交換したいので、正規表現は、うまく機能する場合は、次のとおりです。

+1

となります。 。:) –

8

あなたはスクイズメソッドをしたいです単一のスペース文字。だから、その文字列がsに格納されている場合、その後、あなたはどうなる:

fixed_string = s.gsub(/\s+/, ' ') 
+1

これは正しくはありません。タブの実行を1つのタブに圧縮し、改行を1つの改行に圧縮します。私が読んでいるように、疑問は空白文字の任意の組み合わせの実行を1つの空白文字に置き換える方法を模索しています。 – Chuck

+0

'String.squeeze'は引数としてregexを受け入れていません。あなたがそれが良いアイデアだと思うなら、アップヴォート。私はPRを提出することができます。 – the911s

+2

これは重複を削除します。 "class"は "clas"になります。これは、htmlと言うとこれを実行すると、処理が中断される可能性があります。より適切な方法(レールの場合)は、String#squish – engineerDave

3

選択答えはnon-breaking space文字を削除しません。

これは1.9で動作する必要があります。それは、すべてのスペースを置き換えるよう

fixed_string = s.gsub(/(\s|\u00A0)+/, ' ')

+0

私は、空白文字(つまり複数の空白文字を含む)を削除して、HTML用の文字列のサイズを縮小したいと思っています。複数の連続する空白文字がWebブラウザによって1つのスペースに折りたたまれてしまいます。とにかく...それで、改行しないスペースはHTMLでは無意味ではなく、崩壊しない、つまりおそらく削除したくない – callum

4

を最も簡単な解決策gsub(/\s+/, ' ')との問題は、それが単一であっても、それは非常に遅いことです。しかし、通常は単語の間に1つのスペースがあり、2つ以上の空白が連続している場合にのみ修正する必要があります。

より良い解決策はgsub(/[\r\n\t]/, ' ').gsub(/ {2,}/, ' ')です - あなたはactive_support拡張であるString#squishを、使用することができますRailsの内、通常のスペース

def method1(s) s.gsub!(/\s+/, ' '); s end 
def method2(s) s.gsub!(/[\r\n\t]/, ' '); s.gsub!(/ {2,}/, ' '); s end 

Benchmark.bm do |x| 
    n = 100_000 
    x.report('method1') { n.times { method1("Lorem ipsum\n\n dolor \t\t\tsit amet, consectetur\n \n\t\n adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.") } } 
    x.report('method2') { n.times { method2("Lorem ipsum\n\n dolor \t\t\tsit amet, consectetur\n \n\t\n adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.") } } 
end;1 

#  user  system  total  real 
# method1 4.090000 0.010000 4.100000 ( 4.124844) 
# method2 1.590000 0.010000 1.600000 ( 1.611443) 
11

を最初に特別な空白を取り除く、その後絞ります。

require 'active_support' 

s = <<-EOS 
1/2 cup 

      onion 
EOS 

s.squish 
# => 1/2 cup onion 
関連する問題