age*_*217 9 ruby regex escaping
我正在尝试编写一个与mysqli_real_escape_string
PHP 相同的方法.它需要一个字符串并逃脱任何"危险"的角色.我已经找了一种方法可以为我做这个,但我找不到一个.所以我试着自己写一个.
这就是我到目前为止(我在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
Run Code Online (Sandbox Code Playgroud)
我正在使用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)
Run Code Online (Sandbox Code Playgroud)
有人可以尝试帮助我确定为什么我没有得到我想要的输出(correct_string
)或告诉我在哪里可以找到这样做的方法,或者甚至更好地告诉我两者?非常感谢!
rwi*_*ams 13
您的模式未在示例中正确定义.这就像我可以得到你想要的输出一样接近.
产量
"\\\"My\\\" \\'name\\' \\*is\\* \\-john\\- \\.doe\\. \\/ok?\\/ C:\\\\Drive"
Run Code Online (Sandbox Code Playgroud)
你需要做一些调整才能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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
30141 次 |
最近记录: |