使用Regex和Before_Save删除电子邮件地址

尝试在我的Post模型中使用before_save然后使用正则表达式替换任何看起来像电子邮件的单词’forbidden’。 这是为了减少用户在讨论区中创建的评论/post中的垃圾邮件。

它目前给我一个语法错误; 但我相信它不止于此? 我如何解决它?

Post.rb

before_save :remove_emails # Prevents and replaces any emails or URLs posted by user as  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\.\,\;\?\'\\\+&%\$#\=~_\-]+))*$, "forbidden") end 

根据文件 ,

  1. 没有gsub^function。 你必须使用gsubgsub!
  2. 模式(第一个参数)应该用’/’(斜杠)包围

在gsub之后删除^。

通过对此问题中发布的Regexp进行一些调整,您可以尝试:

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