Ruby:转义字符串中的特殊字符

标签 ruby regex escaping

我正在尝试编写一个与 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) 或者告诉我在哪里可以找到执行此操作的方法,或者最好告诉我两者?非常感谢!

最佳答案

您的示例中的模式定义不正确。这是我所能达到的最接近您期望的输出。

输出

"\\\"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

关于Ruby:转义字符串中的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4140582/

相关文章:

java - 非标准、结构化 CSV - 正则结构

javascript - 如何转义 <span> 或 <div> 标签内的 HTML

ruby-on-rails - 有没有办法控制 ActiveRecord 迁移中的列顺序?

java - 如何使用 Java 数组——从 Ruby 转换为 Java

正则表达式匹配模式而不是值

regex - 通过正则表达式修剪 URL,但不修改为 root

ruby - 续集 gem : Create tables based on schema provided at runtime

javascript - 使用 x 可编辑内联模式自动保存在数据库中,无需在表上添加提交按钮

c++ - Protocol Buffer 文本格式解析器在反斜杠字符上给出错误

python - 我可以在 Linux 中写一个包含路径分隔符的文件名吗?