R gsub用单双引号引起来 [英] R gsub a single double quotation mark
问题描述
我在数据框中有一个字符串字段,它们都类似于:
I have a field of strings in a data frame all similar to:
"Young Adult – 8-9""
其中,内部单号是我想要替换为无用的东西:
where the inner single " is what I want to replace with nothing to get:
"Young Adult - 8-9"
我该怎么做?我试图用双反斜杠转义:
How can I do this? I tried to escape with a double backslash:
gsub("\\"", "", string)
但出现此错误:错误: gsub( \, <中的意外字符串常量/ p>
but got this error: Error: unexpected string constant in "gsub("\"", ""
推荐答案
您无需在正则表达式中转义双引号,只需使用 \
或''
以匹配单引号。
You do not need to escape a double quote in a regular expression. Just use "\""
or '"'
to match a single double quote.
s = "Young Adult – 8-9\""
s
[1] "Young Adult – 8-9\""
gsub("\"", "", s)
[1] "Young Adult – 8-9"
gsub('"', "", s)
[1] "Young Adult – 8-9"
请参见此IDEONE演示
注意:由于您要删除一些 literal 文本,因此您甚至不需要正则表达式,请使用 fixed = TRUE
参数来加快操作速度:
NOTE: Since you want to remove some literal text, you do not even need a regex, use fixed=TRUE
argument to speed up the operation:
gsub('"', "", s, fixed=TRUE)
这篇关于R gsub用单双引号引起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!