使用 gsub 插入反斜杠 [英] Insert backslashes with gsub

查看:42
本文介绍了使用 gsub 插入反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 knitr 输出我的 R 分析,我有一个包含一行下划线的文本.我必须让它们转义,以便将每个 _ 转换为 \_.

I want to output my R analysis with knitr, and I have a text which contains a row of underscores. I have to get them escaped, so to turn every _ into a \_.

但是因为反斜杠也是正则表达式中的一个特殊字符,我没有找到一种方法在每个下划线之前插入一个反斜杠.似乎奇数个反斜杠会产生错误(我猜最后一个与下划线配对)但试图用偶数转义也不起作用.

But because the backslash is also a special character in regex, I did not find a way to actually have a single backslash inserted before each underscore. It seems that odd numbers of backslashes produce an error (I guess the last one gets paired with the underscore) but trying to escape with even numbers didn't work either.

a <- "blah _ blah ___ blah"
> gsub("_", "\\_", a)
[1] "blah _ blah ___ blah"
> gsub("_", "\\\\_", a)
[1] "blah \\_ blah \\_\\_\\_ blah"
> gsub("_", "\\\_", a)
Error: '\_' is an unrecognized escape in character string starting ""\\\_"
> gsub("_", "\_", a)
Error: '\_' is an unrecognized escape in character string starting ""\_"

正确的方法是什么?它不必使用 gsub 和 regex,但我需要轻松地将转义应用于单个字符串.

What is the correct way? It doesn't have to use gsub and regex, but I need the escapes easily applied to a single string.

推荐答案

我们需要转义 \

gsub("_", "\\\\_", a)

如果我们打印出来,它只是一个\

If we print it, it is only a single \

cat(gsub("_", "\\\\_", a))
#blah \_ blah \_\_\_ blah

我们可以通过 nchar

nchar("\\")
#[1] 1

这篇关于使用 gsub 插入反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆