"http:\/\/example.com\/qb-xhtml-v1.xsd"-6ren">
gpt4 book ai didi

ruby - 在 ruby​​ 中转义正斜杠

转载 作者:太空宇宙 更新时间:2023-11-03 16:44:01 24 4
gpt4 key购买 nike

我正在尝试从这样的 URL 中转义正斜杠

"http://example.com/qb-xhtml-v1.xsd" => "http:\/\/example.com\/qb-xhtml-v1.xsd"

但是当我尝试使用 gsub 时,这就是我得到的结果

"http://example.com/qb-xhtml-v1.xsd".gsub("/", '\/')
=> "http:\\/\\/example.com\\/qb-xhtml-v1.xsd"

我也试过

"http://example.com/qb-xhtml-v1.xsd".gsub("/", '/' => '\/')

"http://example.com/qb-xhtml-v1.xsd".gsub(/[\/]/, '\/')

同样的结果。有什么想法吗?

最佳答案

我相信您正在使用的交互式 ruby​​ shell 添加了实际上并不存在的额外反斜杠。

我在 irb 中尝试了你的代码并得到了相同的结果:

irb(main):005:0> "http://example.com/qb-xhtml-v1.xsd".gsub("/", '\/')
"http:\\/\\/example.com\\/qb-xhtml-v1.xsd"

但是如果我使用 puts() 它会正确打印:

irb(main):006:0> puts "http://example.com/qb-xhtml-v1.xsd".gsub('/', '\/')
http:\/\/example.com\/qb-xhtml-v1.xsd
=> nil

我怀疑 ruby​​ shell 只是为了方便而将反斜杠转义,这引起了混淆。

关于ruby - 在 ruby​​ 中转义正斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38357112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com