Ruby:如何使用方括号 [ 和 ] 转义 url? [英] Ruby: How to escape url with square brackets [ and ]?
问题描述
这个网址:
http://gawker.com/5953728/if-alison-brie-and-gillian-jacobs-pin-up-special-doesnt-get-community-back-on-the-air-nothing-will-[nsfw]
应该是:
http://gawker.com/5953728/if-alison-brie-and-gillian-jacobs-pin-up-special-doesnt-get-community-back-on-the-air-nothing-will-%5Bnsfw%5D
但是当我将第一个传递给 URI.encode
时,它不会转义方括号.我也试过 CGI.escape
,但这也转义了所有的/".
But when I pass the first one into URI.encode
, it doesn't escape the square brackets. I also tried CGI.escape
, but that escapes all the '/' as well.
我应该使用什么来正确转义 URL?为什么 URI.encode
不转义方括号?
What should I use to escape URLS properly? Why doesn't URI.encode
escape square brackets?
推荐答案
encode
不转义括号,因为它们并不特殊——它们在 URI 的路径部分没有特殊含义,所以他们实际上并不需要转义.
encode
doesn't escape brackets because they aren't special -- they have no special meaning in the path part of a URI, so they don't actually need escaping.
如果您想转义除不安全"字符以外的字符,请将第二个参数传递给 encode 方法.该 arg 应该是一个正则表达式匹配,或者一个包含您想要编码的每个字符的字符串(包括 字符,否则函数将已经匹配!).
If you want to escape chars other than just the "unsafe" ones, pass a second arg to the encode method. That arg should be a regex matching, or a string containing, every char you want encoded (including chars the function would otherwise already match!).
这篇关于Ruby:如何使用方括号 [ 和 ] 转义 url?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!