Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a string "regexp-safe"

I wan't to make a string regexp safe in Ruby.

I have:

comment = "Just a comment someone makes"
Word.find(:all).each do |word|
  comment.gsub!(%r{#{word}\s*}," ")
end

This replaces all words I've stored in the model Word with an empty space. The problem is if word contains for instance a left parenthesis "(" it will fail. Is there a better way of doing this or at least make word regexp safe? Word may contain any type of character.

Thanks, Martin

like image 256
mrD Avatar asked Dec 21 '09 09:12

mrD


1 Answers

you can use Regexp.escape

like image 92
newacct Avatar answered Sep 29 '22 10:09

newacct