问题
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"
回答1:
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
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"
回答2:
If you want to replace \
symbol with to get
"text with backslash"
, you can try to use gsub
gsub(x ="text with \ backslash",pattern = "\\\\", replacement = "",fixed = T)
For more information of symbol expression, you can check this document in page 59: http://gastonsanchez.com/Handling_and_Processing_Strings_in_R.pdf
来源:https://stackoverflow.com/questions/38583996/using-grep-to-find-strings-with-backslashes-character-escaping