Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

urlencode - How to URL Encode a Backslash with R/RCurl

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("hellohello")
Error: 'h' is an unrecognized escape in character string starting ""helloh"
> curlEscape("hellohello")
Error: 'h' is an unrecognized escape in character string starting ""helloh"
> curlPercentEncode("hellohello")
Error: 'h' is an unrecognized escape in character string starting ""helloh"
> curlPercentEncode("hellohello", amp=TRUE)
Error: 'h' is an unrecognized escape in character string starting ""helloh"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...