Removing Email Address Using Regex and Before_Save

家住魔仙堡 提交于 2019-12-11 15:39:35

问题


Trying to use a before_save in my Post model and then regex to replace anything that looks like an email with the word 'forbidden'. This is to cut down on spam from comments/posts created by users in a discussion board.

It is currently giving me a syntax error; but I am sure it is more than that? How do I fix it?

Post.rb

  before_save :remove_emails

  # Prevents and replaces any emails or URLs posted by user as <forbidden>
  def remove_emails
    self.post = post.gsub^(((ht|f)tp(s?))\://)?(www.|[a-zA-Z].)[a-zA-Z0-9\-\.]+\.(com|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk)(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\;\?\'\\\+&amp;%\$#\=~_\-]+))*$, "forbidden")
  end

回答1:


According to doc,

  1. There is no gsub^ function. you have to use gsub or gsub!
  2. Pattern (first parameter) should be surrounded by '/' (slash)



回答2:


remove the ^ right after gsub.




回答3:


With some adaptations on the Regexp posted in this question, you can try :

# Prevents and replaces any emails or URLs posted by user as <forbidden>
def remove_emails
  self.post.gsub!(/(http|https):\/\/[a-z0-9-\.]+([\-\.]{1}[a-z0-9-\.]+)*[a-z]{2,5}\S*/i, 'forbidden')
end


来源:https://stackoverflow.com/questions/9098591/removing-email-address-using-regex-and-before-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!