【问题标题】:Escape special chars in RegEx?在 RegEx 中转义特殊字符?
【发布时间】:2018-01-03 16:59:33
【问题描述】:

我有一个表单,它将文本字段的内容发送到我的 Rails 应用程序和 我必须生成这个字符串的正则表达式。

我试过这样:

regex = /#{params[:text]}/

一般情况下这是可行的,但如果字符串中包含括号或特殊字符,则此方法将不起作用。

我不希望 Rails 处理这些字符。它们应该被自动转义。

我试过这样:

/\Q#{params[:text]}\E/

但这也不起作用。

【问题讨论】:

    标签: ruby-on-rails ruby regex


    【解决方案1】:

    你应该使用Regexp.escape

    regex = /#{Regexp.escape(params[:text])}/
    # in rails models/controllers with mongoid use:
    # ::Regexp.escape(params[:text]) instead. ([more info][2])
    

    【讨论】:

      【解决方案2】:

      Regexp.escape 转义特殊字符:

      params[:text] = "[foo-bar]"
      Regexp.new(Regexp.escape(params[:text]))
      # => /\[foo\-bar\]/
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-02
        • 2017-03-06
        • 2012-12-15
        • 1970-01-01
        相关资源
        最近更新 更多