r - 如何使用 R/RCurl 对反斜杠进行 URL 编码

标签 r urlencode rcurl

我目前正在尝试对字符串进行编码以插入到 URL 中。我的问题是,当我的字符串包含反斜杠时,这似乎会失败。到目前为止,我已经使用 URLencode、curlEscape(来自 RCurl)和curlPercentEncode(来自 RCurl)函数尝试了 4 种方法,但没有一个成功。

> 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"

最佳答案

您正在寻找

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

您收到的错误不是来自您尝试调用的任何函数;而是来自您尝试调用的任何函数。它并没有真正调用他们中的任何一个。该错误来自 R 的解析器。反斜杠是字符串文字本身的特殊字符,因此您需要在字符串文字中编写一个双反斜杠,以便生成包含反斜杠的字符串值。 (您还可以在反斜杠后面放置其他一些有用的内容;例如,"\"" 是您编写由一个双引号字符组成的字符串值的方式。请阅读 ?Quotes 了解更多信息。)

由于这是字符串文字语法的问题,因此如果您从数据源读取“用于插入 URL 的字符串”,则不应出现该问题;仅当您需要直接在代码中写入此字符串时,这才应该是一个问题。

关于r - 如何使用 R/RCurl 对反斜杠进行 URL 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26304172/

相关文章:

php - Google map 地理编码问题 : Certain Encoded URLs Failing

RCurl getURL SSL 错误

xml - 使用 r httr 从谷歌搜索中抓取 url

r - 异步 POST 请求 - R,使用 RCurl?

r - 创建从 0 到表变量中的值的新列

r - 使用 mapply 获取每个变量的每日数据

r - 使用 devtools::test 时避免重新生成 RcppExports

r - 如何按条件滚动总和?

java - 将 url 编码数据转换为 json

c# - 大写字母的 URL 编码