我目前正在尝试对字符串进行编码以插入到 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"
Run Code Online (Sandbox Code Playgroud)
您正在寻找
> URLencode("hello\\hello")
[1] "hello%5chello"
Run Code Online (Sandbox Code Playgroud)
您收到的错误不是来自您尝试调用的任何函数;而是来自您尝试调用的任何函数。它并没有真正打电话给他们中的任何一个。该错误来自 R 的解析器。反斜杠是字符串文字本身的特殊字符,因此您需要在字符串文字中编写双反斜杠才能生成包含反斜杠的字符串值。(您还可以在反斜杠后放置其他一些有用的内容;例如,"\""如何编写由一个双引号字符组成的字符串值。请阅读?Quotes以获取更多信息。)
由于这是字符串文字语法的问题,因此如果您从数据源读取“用于插入 URL 的字符串”,则不应出现此问题;仅当您需要直接在代码中写入此字符串时,这才应该成为问题。