R: strsplit on backslash (\)

后端 未结 1 1994
一个人的身影
一个人的身影 2020-12-17 22:32

I am trying to extract the part of the string before the first backslash but I can\'t seem to get it tot work properly.

I have tried multiple ways of getting it to

相关标签:
1条回答
  • 2020-12-17 22:55

    If you use a regex with strsplit function, a literal backslash can be coded as two literal backslashes (as a literal \ is a special regex metacharacter that is used to form regex escapes, like \d, \w, etc.), but since R string literals support string escape sequences (like "\r" for carriage return, "\n" for a newline char) a literal backslash needs to be defined with a double backslash.

    So, "\\" is a literal \, and a regex pattern to match a literal backslash char, being \\, should be coded with 4 backslashes, "\\\\".

    Here is a regex that you can use: it splits at \ and a non-printable character:

    strsplit("BLAAT1\022E:\\BLAAT2\\BLAAT3","\\\\|[^[:print:]]",fixed=FALSE)
    # [1] "BLAAT1" "E:"     "BLAAT2" "BLAAT3"
    

    See IDEONE demo

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