/ / Rubyで文字列を検索して置換する最速の方法は? -ruby-on-rails、ruby、regex、string

Rubyで文字列を検索して置換する最速の方法は? - ルビーオンレール、ルビー、正規表現、文字列

私は、ユーザーが生成したコンテンツをクリーンアップし、何千もの文字列を置き換えるライブラリを構築しています(パフォーマンスが重要です)。

何が 最も速い 文字列で検索と置換を行う方法は?

ライブラリが行う置換の例を次に示します。

u2 => you too
2day => today
2moro => tomorrow
2morrow => tomorrow
2tomorow  => tomorrow

文字列の表示方法には4つのケースがあります。

  • 文字列内の開始単語(最後にスペースがありますが、その前にはありません) 2day sample
  • ストリングの中央(前と末尾にスペースがあります) sample 2day sample
  • 文字列の終わり(前にスペースのみがありますが、最後の単語です) sample 2day
  • 文字列全体が一致 2day

すなわち正規表現 すべきではない 次のような単語の途中にある場合は置き換えます sample2daysample

回答:

回答№1は2

可能な解決策:

replaces = {"u2" => "you too", "2day" => "today", "2moro" => "tomorrow"}

str = "2day and 2moro are u2 sample2daysample"

#exp = Regexp.union(replaces.keys)  #it is the best but to use b this should be a quiet different
exp = Regexp.new(replaces.keys.map { |x| "\b" + Regexp.escape(x) + "\b" }.join("|"))
str = str.gsub(exp, replaces)

# => "today and tomorrow are you too sample2daysample"