读取带有单引号和双引号的字符串

Read a string with single and doubles quotes

只是夏季对 R 中的字符串的好奇心。假设我有一个 xy 字符串。正如我们所知,我们必须在双引号中引用单引号,反之亦然。

x <- "a string with 'single' quotes"
y <- 'another one with "double" quotes'

paste0(x, y)
[1] "a string with 'single' quotesanother one with \"double\" quotes"
cat(x, y)
a string with 'single' quotes another one with "double" quotes

如果我们也有一个带有单引号和双引号的字符串怎么办?我试过这个: 反引号不起作用(R 触发错误):

z <- `a string with 'single' quotes and with "double" quotes`

使用 \" 代替 ",然后使用 cat: 这很好用,但问题是用户必须为每个双引号添加反斜杠。

z1 <- "a string with 'single' quotes and with \"double\" quotes"

如果我们有一个巨大的 text 文件(例如 .txt)并且我们想在 R 中读取这两种类型的引号怎么办?

在这一点上,对我来说一个(愚蠢的)解决方案似乎是:在 R 之外工作,做一些操作(比如用 \" 替换所有 ")然后在 R 中读取。 这是一个解决方案还是在 R 中确实存在更好的方法?

这里只是一个小 .txt 文件,例如:Link,无论如何,对于感兴趣的人,该文件只是一个 .txt,其中一行包含以下文本:

a string with 'single' quotes and with \"double\" quotes

您可以在阅读文本时根据需要指定任何替代引号字符,例如

> p<-scan(what="character",quote="`")
1: `It is 'ambiguous' if "this is a new 'string' or "nested" in the 'first'", isn't it?`
2: 
Read 1 item
> p
[1] "It is 'ambiguous' if \"this is a new 'string' or \"nested\" in the 'first'\", isn't it?"

或者,只阅读原始文本,例如按照@rawr

的建议使用 readline
> readline()
 "It is 'ambiguous' if "this is a new 'string' or "nested" in the 'first'", isn't it?"
[1] "\"It is 'ambiguous' if \"this is a new 'string' or \"nested\" in the 'first'\", isn't it?\""