如何使用R/RCurl对URL进行反斜杠编码 [英] How to URL Encode a Backslash with R/RCurl

查看:348
本文介绍了如何使用R/RCurl对URL进行反斜杠编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"

推荐答案

您正在寻找

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

您得到的错误不是来自您尝试调用的任何函数;它没有达到实际调用任何一个的程度.错误来自R的解析器.反斜杠是字符串文字本身的特殊字符,,因此您需要在字符串文字中编写 double 反斜杠,以生成包含反斜杠的字符串值. (您还可以在反斜杠后面添加其他有用的内容;例如,"\""是编写包含一个双引号字符的字符串值的方法.有关更多信息,请阅读?Quotes.)

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.)

由于这是字符串文字的语法问题,因此,如果您正在从数据源中读取用于插入URL的字符串",则不会出现此错误;仅当您需要直接在代码中编写此字符串时,这才是问题.

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.

这篇关于如何使用R/RCurl对URL进行反斜杠编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆