使用grep查找带有反斜杠的字符串-字符转义 [英] using grep to find strings with backslashes - Character Escaping

查看:759
本文介绍了使用grep查找带有反斜杠的字符串-字符转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难在正则表达式中使用 \ 作为聊天工具。任何想法如何使它起作用?

I am having difficulties to use \ as a chatterer within a regular expression. Any ideas how to make that work?

grep(pattern = '\', "text with \ backslash", value = T )
# Expected output: [1] "text with  backslash"


推荐答案

R字符串中的单个 \ 无效,因为 \ 是转义字符。一个反斜杠实际上由两个反斜杠 \\ 表示。第一个用作转义字符,第二个是实际的反斜杠。函数 cat 可用于打印最终字符串(与内部R表示法相反)。

A single \ in an R string is invalid because \ is an escape character. A single backslash is actually represented by two backslashes \\. The first one serves as an escape character, the second one is the actual backslash. The function cat can be used to print the final string (in contrast to the internal R representation).

text <- "text with \\ backslash"
text
# [1] "text with \\ backslash"
cat(text)
# text with \ backslash

因为R字符串中的单个反斜杠表示加上两个反斜杠 \\ ,则需要四个反斜杠 \ 在您的正则表达式中。这是因为 \ 也是正则表达式中的转义字符。因此, \ 可以解释为 \\ 的两倍。

Because a single backslash in an R string is represented by two backslashes \\, you need four backslashes \\\\ in your regular expression. This is due to \ being an escape character in regular expressions as well. Hence, \\\\ can be interpreted as two times \\.

grep(pattern = '\\\\', text, value = TRUE)
# [1] "text with \\ backslash"

这篇关于使用grep查找带有反斜杠的字符串-字符转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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