开发者

Make a string "regexp-safe"

开发者 https://www.devze.com 2022-12-14 08:01 出处:网络
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|

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 o开发者_如何转开发r at least make word regexp safe? Word may contain any type of character.

Thanks, Martin


you can use Regexp.escape

0

精彩评论

暂无评论...
验证码 换一张
取 消