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

时间:2022-10-28 15:01:06

Just summertime curiosity about strings in R. Let use say that I have a x and y strings. As we know we have to quote single quotes in double quotes and vice versa.

只是夏天对r中弦的好奇假设我有x和y弦。正如我们所知,我们必须引用双引号中的单引号,反之亦然。

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

What if we have a string with single and double quotes too? I have tried this: Backticks do not work (R triggers an error):

如果我们有一个单引号和双引号的字符串呢?我尝试过:仰卧起坐不起作用(R触发一个错误):

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

Use a \" instead of " and then use cat: This works well but the problem is that users must add a backslash to every double quote.

使用一个\“代替”,然后使用cat:这很有效,但是问题是用户必须在每个双引号中添加反斜杠。

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

what if we have a huge text file (like a .txt for example) with both type of quotes and we want to read in R?

如果我们有一个很大的文本文件(例如.txt),包含两种类型的引号,并且我们想要在R中读取,该怎么办?

At this point a (silly) solution to me seems to be: work outside R, do some manipulations (like substitute all " with \") and then read in R. Is this a solution or does exist a better way inside R?

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

Here is just a little .txt file for example: Link, anyways for who is interested, the file is just a .txt with one line with this text:

这里有一个小的。txt文件,例如:Link,无论如何,对于感兴趣的人来说,这个文件只是一个。txt,只有一行文本:

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

带有“单”引号和“双\”引号的字符串

1 个解决方案

#1


2  

You may specify any alternate quoting characters as desired when reading text, e.g.

当你阅读文本时,你可以指定任意的引用字符。

> 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?"

Or, just read raw text, e.g. with readline as suggested by @rawr

或者,阅读原始文本,如@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?\""

#1


2  

You may specify any alternate quoting characters as desired when reading text, e.g.

当你阅读文本时,你可以指定任意的引用字符。

> 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?"

Or, just read raw text, e.g. with readline as suggested by @rawr

或者,阅读原始文本,如@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?\""