using grep to find strings with backslashes - Character Escaping

前端 未结 2 1723

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

grep(pattern = \'\\\', \"text w         


        
相关标签:
2条回答
  • 2021-01-14 11:27

    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"
    
    0 讨论(0)
  • 2021-01-14 11:45

    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

    0 讨论(0)
提交回复
热议问题