简体   繁体   中英

How to store a special character in a string in R

I am trying to store the special escape character \\ in R as part of a string.

x = "abcd\efg"

# Error: '\e' is an unrecognized escape in character string starting ""abcd\e"

x = "abcd\\efg"

# Works

The problem is that x is actually a password that I am passing as part of an API web call so I need to find a way for the string to store a literal single slash in order for this to work.

Example using the ignoring literal command:

> x = r"(abcd\efg)"

> y = "https://url?password="

> paste(x, y, sep = "")
[1] "abcd\\efg123"

> # What I need is for it to return
[1] "abcd\efg123"

> z = paste(y, x, sep = "")

> z
[1] "https://url?password=abcd\\efg"

> cat(z)
https://url?password=abcd\efg

When I pass z as part of the API command I get "bad credentials" message because it's sending \\\\ as part of the string. cat returns it to the console correctly, but it appears to not be sending it the same way it's printing it back.

Like everyone else in the comments said, the string appears to be handled correctly by R. I would assume it becomes a trouble somewhere else down the line. Either the API or the pass-matching software itself might be doing something with it.

As one example, the backslash will not work in most browsers if written verbatim, you would need to use %5C instead. Here is one discussion about it.

So in your case - try replacing the backslash with something else, either %5C or, as @Roland mentioned in the comments, some extra back-slash symbols, like \\\\\\\\ or \\\\\\ or \\\\ . And then see if any of them work.

The answers and comments contain the solution, but for completeness ill post an answer that matches my specific situation.

My package expects the user to supply a password. If there is a \\ in the password the command will fail as stated above. The solution seems to be to take care of it on the input rather than trying to alter the value once the user submits the password.

library(RobinHood)

# If the true password is: abc\def

# The following inputs will all work
rh <- RobinHood("username", pwd = r"(abc\def)")
rh <- RobinHood("username", pwd = "abc\\def")
rh <- RobinHood("username", pwd = "abc%5Cdef")


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM