【问题标题】:Removing Email Address Using Regex and Before_Save使用 Regex 和 Before_Save 删除电子邮件地址
【发布时间】:2012-02-01 15:35:16
【问题描述】:

尝试在我的 Post 模型中使用 before_save,然后使用正则表达式将任何看起来像电子邮件的内容替换为“禁止”一词。这是为了减少来自用户在讨论区中创建的 cmets/帖子的垃圾邮件。

它目前给我一个语法错误;但我敢肯定它不止于此?我该如何解决?

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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1


    【解决方案1】:

    根据doc,

    1. 没有gsub^ 函数。你必须使用gsub 或gsub!
    2. 模式(第一个参数)应该用“/”(斜杠)括起来

    【讨论】:

      【解决方案2】:

      删除 gsub 之后的 ^。

      【讨论】:

      • 仍然抛出语法错误.. =[我认为这与 Ruby 代码的实际格式有关,我怀疑?
      【解决方案3】:

      对 this question 中发布的 Regexp 进行了一些修改,您可以尝试:

      # 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
      

      【讨论】:

        猜你喜欢
        • 2011-10-28
        • 2015-01-23
        • 1970-01-01
        • 1970-01-01
        • 2019-12-17
        • 1970-01-01
        • 1970-01-01
        • 2018-04-16
        • 2019-05-05
        相关资源
        最近更新 更多