在R中用`\&`替换`&`。

huangapple go评论155阅读模式
英文:

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>

huangapple
  • 本文由 发表于 2023年7月20日 21:43:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76730523.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定