2014-10-10 100 views
1

我正在嘗試編碼字符串以便插入到URL中。我的問題是,當我的字符串包含反斜槓時,這似乎失敗。到目前爲止,我已經嘗試了4種使用URLencode,curlEscape(來自RCurl)和curlPercentEncode(來自RCurl)函數的方法,但都沒有成功。如何URL使用R/RCurl對反斜槓進行編碼

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

你試過'URLencode(「hello \\ hello」)'? – 2014-10-10 16:45:30

回答

2

你從任何你想調用的函數尋找

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

你得到該錯誤不;它沒有達到實際調用它們中的任何一個。錯誤來自R的解析器。反斜槓是字符串本身的一個特殊字符,因此,您需要在字符串字面值中編寫一個反斜槓,以便生成包含反斜槓的字符串值。 (在反斜槓之後可以使用其他幾個有用的東西;例如,"\""是如何編寫一個由雙引號字符組成的字符串值。)

由於這是一個問題字符串文字的語法,如果您正在閱讀數據源中的「插入到URL中的字符串」,則不應出現這種情況;它只應該是一個問題,如果你需要直接在你的代碼中寫這個字符串。