简体   繁体   English

用 R 中的 gsub 替换

[英]replace with gsub in R

I would like to convert string \\\\xAB\\\\xAC to \\xAB\\xAC in R.我想在 R \\xAB\\xAC字符串\\\\xAB\\\\xAC转换为\\xAB\\xAC

When I'm using gsub("\\\\\\\\", "$", x) I'm getting $AB$AC which is expectable.当我使用gsub("\\\\\\\\", "$", x)我得到$AB$AC这是可以预料的。
But when I'm using gsub("\\\\\\\\", "\\\\", x) I'm getting only ABAC .但是当我使用gsub("\\\\\\\\", "\\\\", x)我只得到ABAC
Is where a way to workaround this?哪里有办法解决这个问题?

As per akrun's comment, you can use cat(x) to see/view the 'single' backslashed strings.根据 akrun 的评论,您可以使用cat(x)查看/查看“单个”反斜杠字符串。 The reason is that a single literal backslash is represented with two inside the R string literal.原因是单个文字反斜杠在 R 字符串文字中用两个表示。 cat will "unescape" the string. cat将“取消转义”字符串。

To double a single literal backslash, use要将单个文字反斜杠加倍,请使用

x <- "\\ backslash doubled here"
cat(gsub("\\\\", "\\\\\\\\", x), collapse="\n")
# => \\ backslash doubled here 
cat(gsub("\\", "\\\\", x, fixed=TRUE), collapse="\n")
# => \\ backslash doubled here 

See the R demo .请参阅R 演示

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

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