Skip to content

Backslash

2 messages · Josef Eschgfaeller, Duncan Murdoch

#
Why sometimes one has to put a double
backslash in regular expressions, but
often simple backslashes work too?
Is only a \ required for giving a
metacharacter its usual meaning?
---------------------------------------
u=grep('\\{[\\-u]x',a,perl=T)

       # equivalent to

u=grep('\{[\-u]x',a,perl=T)

       # but

u=grep('\w',a,perl=T)

       # is not correct and requires

u=grep('\\w',a,perl=T)
---------------------------------------
Josef Eschgf??ller
#
Josef Eschgfaeller wrote:
The general reason is that both R and grep use \ as an escape character. 
  If you want to send an escape to grep you need to escape the escape in R.
No.  The first one passes the string containing "\{[\-u]x" to grep 
(after processing the escapes).  The second one passes "{[-u]x" to grep.
\w has no special meaning in R, so this pattern becomes "w".
This is the pattern "\w".  I don't know if this has special meaning to 
pcre, but I guess it must, or you wouldn't have tried it.

Duncan Murdoch