How to URL Encode a Backslash with R/RCurl

半城伤御伤魂 提交于 2019-11-28 10:29:07

问题


I'm currently trying to encode a string for insertion into a URL. My issue is that this seems to fail when my string contains a backslash. I've tried 4 approaches so far using the URLencode, curlEscape (from RCurl), and curlPercentEncode (from RCurl) functions, but none of them have been successful.

> URLencode("hello\hello")
Error: '\h' is an unrecognized escape in character string starting ""hello\h"
> curlEscape("hello\hello")
Error: '\h' is an unrecognized escape in character string starting ""hello\h"
> curlPercentEncode("hello\hello")
Error: '\h' is an unrecognized escape in character string starting ""hello\h"
> curlPercentEncode("hello\hello", amp=TRUE)
Error: '\h' is an unrecognized escape in character string starting ""hello\h"

回答1:


You are looking for

> URLencode("hello\\hello")
[1] "hello%5chello"

The error you're getting is not from any of the functions you tried to call; it didn't get as far as actually calling any of them. The error is from R's parser. Backslash is a special character for string literals themselves, so you need to write a double backslash in your string literal in order to produce a string value containing a backslash. (There are several other things you can usefully put after the backslash; for instance, "\"" is how you write a string value consisting of one double-quote character. Read ?Quotes for further information.)

Since this is an issue with the syntax of string literals, it shouldn't come up if you're reading the "string for insertion into a URL" from a data source; it should only be an issue if you need to write this string directly in your code.



来源:https://stackoverflow.com/questions/26304172/how-to-url-encode-a-backslash-with-r-rcurl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!