[R] Backslash

Duncan Murdoch murdoch at stats.uwo.ca
Mon May 23 17:49:01 CEST 2005


Josef Eschgfaeller wrote:
> 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?

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.

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

No.  The first one passes the string containing "\{[\-u]x" to grep 
(after processing the escapes).  The second one passes "{[-u]x" to grep.
> 
>        # but
> 
> u=grep('\w',a,perl=T)

\w has no special meaning in R, so this pattern becomes "w".
> 
>        # is not correct and requires
> 
> u=grep('\\w',a,perl=T)

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

> ---------------------------------------
> Josef Eschgfäller
> 
> 
> 
> ------------------------------------------------------------------------
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html




More information about the R-help mailing list