简体   繁体   English

如何在R中的字符串中存储特殊字符

[英]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.我试图将特殊转义字符\\作为字符串的一部分存储在 R 中。

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.问题是x实际上是我作为 API Web 调用的一部分传递的密码,因此我需要找到一种方法让字符串存储文字单斜杠,以便使其正常工作。

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.当我将z作为 API 命令的一部分传递时,我收到“错误凭据”消息,因为它将\\\\作为字符串的一部分发送。 cat returns it to the console correctly, but it appears to not be sending it the same way it's printing it back. cat正确地将它返回到控制台,但它似乎没有像打印回来那样发送它。

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.就像评论中的其他人所说的那样,该字符串似乎由 R 正确处理。我认为它会成为其他地方的麻烦。 Either the API or the pass-matching software itself might be doing something with it. API 或通过匹配软件本身可能会用它做一些事情。

As one example, the backslash will not work in most browsers if written verbatim, you would need to use %5C instead.举个例子,如果逐字书写,反斜杠在大多数浏览器中不起作用,您需要使用%5C代替。 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 \\\\ .所以你的情况-尝试用别的东西代替反斜杠,要么%5C或者如@Roland在评论中提到的,一些额外的反斜杠符号,像\\\\\\\\\\\\\\\\\\ 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")


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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