2012-04-30 18 views
1

配列に複数の正規表現の置換をしたいのですが、私はこの作業用コードを持っていますが、それはルビー型ではないようです。ruby​​複数の正規表現の置換を自動化

#files contains the string that need cleaning 
files = [ 
    "Beatles - The Word ", 
    "The Beatles - The Word", 
    "Beatles - Tell Me Why", 
    "Beatles - Tell Me Why (remastered)", 
    "Beatles - Love me do" 
] 

#ignore contains the reg expr that need to bee checked 
ignore = [/the/,/\(.*\)/,/remastered/,/live/,/remix/,/mix/,/acoustic/,/version/,/ +/] 

files.each do |file| 
    ignore.each do |e| 
    file.downcase! 
    file.gsub!(e," ") 
    file.strip! 
    end 
end 
p files 
#=>["beatles - word", "beatles - word", "beatles - tell me why", "beatles - tell me why", "beatles - love me do"] 
+0

をあなたが使用して説明したすべての単語に一致する単一の正規表現を作成することができます。「|」 –

答えて

0

私はこの解決策を2つのバージョンから作成しました.1つは文字列に変換されます(ファイル配列は変更されず、ファイル配列自体が変更されるArrayの拡張が1つあります)。 。ONYONEはまだ提案されている場合は、それらを共有してください

files = [ 
    "Beatles - The Word ", 
    "The Beatles - The Word", 
    "Beatles - Tell Me Why", 
    "The Beatles - Tell Me Why (remastered)", 
    "Beatles - wordwiththein wordwithlivein" 
] 

ignore = /\(.*\)|[_]|\b(the|remastered|live|remix|mix|acoustic|version)\b/ 

class Array 
    def cleanup ignore 
    self.each do |e| 
     e.downcase! 
     e.gsub!(ignore," ") 
     e.gsub!(/ +/," ") 
     e.strip! 
    end 
    end 
end 

p files.join("#").downcase!.gsub(ignore," ").gsub(/ +/," ").split(/ *# */) 
#=>["beatles - word", "beatles - word", "beatles - tell me why", "beatles - tell me why", "beatles - wordwiththein wordwithlivein"] 

Benchmark.bm do |x| 
    x.report("string method") { 10000.times { files.join("#").downcase!.gsub(ignore," ").gsub(/ +/," ").split(/ *# */) } } 
    x.report("class method") { 10000.times { files.cleanup ignore } } 
end 

=begin 
     user  system  total  real 
string method 0.328000 0.000000 0.328000 ( 0.327600) 
class method 0.187000 0.000000 0.187000 ( 0.187200) 
=end 
1

これらのほとんどを単一のregex replace操作に入れることができます。また、単語境界アンカー(\b)を使用する必要があります。たとえば、theThere's a Placeと一致します。

file.gsub!(/(?:\b(?:the|remastered|live|remix|mix|acoustic|version)\b)|\([^()]*\)/, ' ') 

がこれを処理します。

その後、あなたは第二段階で複数のスペースを取り除くことができます。

file.gsub!(/ +/, ' ') 

を使用すると、配列内の正規表現を維持したい場合は、各正規表現のための代替品を配列を反復処理し、何をする必要があります。しかし、あなたは、少なくともループの外にいくつかのコマンドを実行できます。

もちろん
files.each do |file| 
    file.downcase! 
    ignore.each do |e| 
    file.gsub!(e," ") 
    end 
    file.strip! 
end 

、その後、あなたはあなたの無視リスト内の各単語の周りにワード境界を配置する必要があります:

ignore = [/\bthe\b/, /\([^()]*\)/, /\bremastered\b/, ...] 
+0

このつもりですbecouse私は別の配列のパターンをokeepしたいと思いますこれらの例よりもはるかに大きく、私はそれを読みやすくしておきたいと思います。単語のバウンスについては – peter

3
ignore = ["the", "(", ".", "*", ")", "remastered", "live", "remix", "mix", "acoustic", "version", "+"] 
re = Regexp.union(ignore) 
p re #=> /the|\(|\.|\*|\)|remastered|live|remix|mix|acoustic|version|\+/ 

Regexp.unionエスケープしてくれます。

+1

+1ですが、元の配列を使用してください。これらのいくつかは正規表現ではありません。傷ついた; 'ignore = [/ \ bthe \ b /、/\(.*\)/、...]'という単語境界を使うべきです。 –