[R] Escaping regular expressions

Gabor Grothendieck ggrothendieck at gmail.com
Fri Nov 13 15:50:13 CET 2009


This is not minimal (it will escape every non-word character) but is
short and the needlessly escaped ones should do no harm (though you
might want to double check that assumption on a few examples):

gsub("(\\W)", "\\\\\\1", x)

On Fri, Nov 13, 2009 at 8:33 AM, Hadley Wickham <hadley at rice.edu> wrote:
> Hi all,
>
> Is there a method for escaping strings to be used regular expressions?
>  i.e. if I have a user supplied string that I'd like to use as a fixed
> component is there a method that will turn (e.g.) ".$^" into
> "\\.\\$\\^" ?
>
> Thanks,
>
> Hadley
>
> --
> http://had.co.nz/
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list