英文:
Replace `&` with `\&` in R
问题
我想在R&D
中替换&
为\&
。
我该如何做?
stringr::str_replace("R&D","&","\\&")
仍然返回R&D
而不是R\&D
,我不知道为什么。
英文:
I want to replace &
with \&
in R&D
.
How can I do it?
stringr::str_replace("R&D","&","\\&")
still gives R&D
instead of R\&D
, I don't know why.
答案1
得分: 5
&
在 str_replace
的替换值中具有特殊意义(它指的是匹配的文本)。为了避免这种特殊意义,需要双倍斜杠来转义它们。
因此,以下方法有效:
stringr::str_replace("R&D", "&", "\\\\&")
英文:
\&
has a special meaning in the replacement value of str_replace
(it refers to the matched text). To avoid this special meaning, double up the backslashes to escape them, too.
The following therefore works:
stringr::str_replace("R&D", "&", "\\\\&")
答案2
得分: 2
@Konrad Rudolph已经给出了完美的解释。如果您想打印一个单反斜杠,您可以使用cat
。这里是另一种使用gsub
的方法:
cat(gsub("&", "(\\&)", "R&D"))
#> R\&D
创建于2023-07-20,使用reprex v2.0.2
英文:
@Konrad Rudolph already gave a perfect explanation. If you want to print a single backslash you could use cat
. Here is an alternative using gsub
:
cat(gsub("&", r"(\\&)", "R&D"))
#> R\&D
<sup>Created on 2023-07-20 with reprex v2.0.2</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论