【问题标题】:Ruby: Escaping special characters in a stringRuby:转义字符串中的特殊字符
【发布时间】:2011-05-07 15:16:16
【问题描述】:

我正在尝试编写一个与 PHP 中的mysqli_real_escape_string 相同的方法。它需要一个字符串并转义任何“危险”字符。我一直在寻找一种可以为我做到这一点的方法,但我找不到。所以我想自己写一个。

这就是我目前所拥有的(我在Rubular.com 测试了该模式并且它有效):

# Finds the following characters and escapes them by preceding them with a backslash. Characters: ' " . * / \ -
def escape_characters_in_string(string)
  pattern = %r{ (\'|\"|\.|\*|\/|\-|\\) }
  string.gsub(pattern, '\\\0') # <-- Trying to take the currently found match and add a \ before it I have no idea how to do that).
end

我使用start_string 作为我要更改的字符串,并使用correct_string 作为我希望start_string 变成的字符串:

start_string = %("My" 'name' *is* -john- .doe. /ok?/ C:\\Drive)
correct_string = %(\"My\" \'name\' \*is\* \-john\- \.doe\. \/ok?\/ C:\\\\Drive)

有人可以帮我确定为什么我没有得到我想要的输出 (correct_string),或者告诉我在哪里可以找到一种方法,或者更好地告诉我这两个?非常感谢!

【问题讨论】:

  • 所以您将start_string 放入escape_characters_in_string 中却没有得到您所期待的结果?那不正确的输出是什么?你已经给了我们你期望看到的东西,现在告诉使用你实际看到的......
  • 当我putsescape_characters_in_string(start_string)的结果时,没有任何变化;它打印出start_string 的内容

标签: ruby regex escaping


【解决方案1】:

您的示例中的模式定义不正确。这是尽可能接近您想要的输出。

输出

"\\\"My\\\" \\'name\\' \\*is\\* \\-john\\- \\.doe\\. \\/ok?\\/ C:\\\\Drive"

您需要进行一些调整才能使其达到 100%,但至少您现在可以看到您的模式正在发挥作用。

  def self.escape_characters_in_string(string)
    pattern = /(\'|\"|\.|\*|\/|\-|\\)/
    string.gsub(pattern){|match|"\\"  + match} # <-- Trying to take the currently found match and add a \ before it I have no idea how to do that).
  end

【讨论】:

    【解决方案2】:

    我把上面的函数改成这样:

      def self.escape_characters_in_string(string)
        pattern = /(\'|\"|\.|\*|\/|\-|\\|\)|\$|\+|\(|\^|\?|\!|\~|\`)/
        string.gsub(pattern){|match|"\\"  + match}
      end
    

    这非常适合正则表达式

    【讨论】:

      【解决方案3】:

      这应该让你开始:

      print %("'*-.).gsub(/["'*.-]/){ |s| '\\' + s }
      \"\'\*\-\.
      

      【讨论】:

        【解决方案4】:
        【解决方案5】:

        看一下Mysql类here中的escape_string/quote方法

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-05-11
          • 1970-01-01
          • 2017-12-01
          • 2016-01-05
          • 1970-01-01
          • 1970-01-01
          • 2021-01-09
          相关资源
          最近更新 更多