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

前端之家收集整理的这篇文章主要介绍了Ruby:转义字符串中的特殊字符前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试编写一个与 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
原文链接:https://www.f2er.com/ruby/269163.html

猜你在找的Ruby相关文章