我在使用\
作为正则表达式内的一个语句时遇到困难。任何想法如何使这项工作?使用grep查找带反斜杠的字符串 - 字符溢出
grep(pattern = '\', "text with \ backslash", value = T)
# Expected output: [1] "text with backslash"
我在使用\
作为正则表达式内的一个语句时遇到困难。任何想法如何使这项工作?使用grep查找带反斜杠的字符串 - 字符溢出
grep(pattern = '\', "text with \ backslash", value = T)
# Expected output: [1] "text with backslash"
在R串的单个\
是无效的,因为\
是转义字符。单个反斜杠实际上由两个反斜杠\\
表示。第一个是转义字符,第二个是实际的反斜线。函数cat
可用于打印最终字符串(与内部R表示形式相反)。
text <- "text with \\ backslash"
text
# [1] "text with \\ backslash"
cat(text)
# text with \ backslash
因为在R字符串中的一个反斜杠用两个反斜线\\
代表,你需要在你的正则表达式反斜杠\\\\
。这是由于\
也是正则表达式中的转义字符。因此,\\\\
可以解释为两次\\
。
grep(pattern = '\\\\', text, value = TRUE)
# [1] "text with \\ backslash"
如果你想更换\
符号得到"text with backslash"
,你可以尝试使用gsub
gsub(x ="text with \ backslash",pattern = "\\\\", replacement = "",fixed = T)
对于符号表达的更多信息,你可以在59页查看本文档: http://gastonsanchez.com/Handling_and_Processing_Strings_in_R.pdf
谢谢斯文。这非常有帮助。 – Deena