5
>str= "AAC|Australia Acquisition Corp. - Ordinary Shares|S|N|D|100"
> strsplit(str,"\\|")
[[1]]
[1] "AAC"                                          
[2] "Australia Acquisition Corp. - Ordinary Shares"
[3] "S"                                            
[4] "N"                                            
[5] "D"                                            
[6] "100"   

I wonder \\| is equal to | ?
maybe \\|is equal to \| ,
why can strsplit(str,"\\|") work?

3 Answers 3

17

Since

|

has a special meaning in reg-exps it needs to be escaped, so to match | the actual regular expression is

\|

Since \ in turn is a special character when declaring string literals (you probably recognize it from \n etc.), the \ needs to be escaped itself. I.e., in order to create a string literal containing \| you need

\\|
1
  • 1
    I prefer to think of the representation in reverse; but yeah, what @aioobe said.
    – dlamblin
    Aug 4, 2012 at 7:36
7

Because it's a quoted string. In a quoted string, you can include a " character by escaping it with a \. A \ itself then also needs to be escaped to be a single literal backslash. So your quoted string means: \|.

Now in a regular expression a | is a special character that is not matched literally unless it is escaped. Regular Expressions in R also escape with a backslash, so the string literal "\\|" means the string \| which is an expression matching exactly |. Why "\\|" works is because that means matching exactly | which appears as the separator in the string you're splitting.

A more specific reference to regular expressions in R might be handy, but it, as many do, references perl regular expressions.

2
  • I think your second sentence about how to include a " is nothing but confusing.
    – aioobe
    Aug 4, 2012 at 7:51
  • @aioobe really? there's no other reason a backslash wouldn't otherwise be literally a backslash if not for the fact that it is the escape character. And it is the escape character so that you can include quotes within quotes. All the special escaped characters, like the common newline, could be included literally, and are in several languages.
    – dlamblin
    Aug 4, 2012 at 7:55
0

From the paltry little I know about regex, I think "\|" itself would work (backslash to escape pipe. Source: Regular Expressions Reference

1
  • 1
    It would. The thing is that \ is a special character in R, so the string \| is denoted by \\| as a string literal in R. Aug 4, 2012 at 8:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.