如何用“ \&”替换“&”

问题描述 投票:1回答:1

[我发现使用R的"&" "\&"函数很难用base替换gsub()-

gsub("&", "\&", "A&B")

给出以下错误-

Error: '\&' is an unrecognized escape in character string starting ""\&"

有没有办法实现这种替代?

r regex gsub
1个回答
0
投票

您可以使用

gsub("&", "\\&", "A&B",fixed=TRUE) # Fixed string replacement
gsub("(&)", "\\\\\\1", "A&B")      # Regex replacement

结果仅包含一个反斜杠,您可以轻松地使用cat或将内容保存到文本文件中进行检查:

cat(gsub("&", "\\&", "A&B",fixed=TRUE), collapse="\n")
cat(gsub("(&)", "\\\\\\1", "A&B"))

请参见R demo online

© www.soinside.com 2019 - 2024. All rights reserved.