[R] detect escape character

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Tue Jun 3 20:50:57 CEST 2014


With the right mental model, though, it can become intuitive. That is, keep in mind that the R interpreter uses \ as a metacharacter, and so does the regex library. You want to search for a \, which regex thinks is special, so you have to escape it for regex functions (\\). Then, because R thinks \ is special, you have to escape each of those ("\\\\") in your source file to get a pair of backslashes in memory to give to regex functions.

To practice, always think of an opening quote mark as an opportunity watch for backslashes and mentally remove the first one and change the following character to whatever it should be  to picture what is in memory. Use the print function to see how R wants you to toe it in, and use the cat function to see how it looks in memory.
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.

On June 3, 2014 11:18:14 AM PDT, Sarah Goslee <sarah.goslee at gmail.com> wrote:
>Hi,
>
>R uses \ as a metacharacter, so you need a non-intuitive number of \:
>
>
>mystring <- "Man\\Woman"
># \\ is a metacharacter and a \, so it's equivalent to \ in normal text
>sub("\\\\", "/", mystring)
>
>
>Sarah
>
>
>On Tue, Jun 3, 2014 at 2:03 PM, Adrian Dușa <dusa.adrian at unibuc.ro>
>wrote:
>> Dear All,
>>
>> I should be knowing this, but not get it right... For a string like
>this:
>>
>> "Man\Woman"
>>
>> I would like to detect the escape character "\" and replace it with
>"/".
>>
>> Tried various ways using gsub(), but don't get it right yet. Any
>suggestion
>> would be highly welcomed...
>>
>> Thank you,
>> Adrian
>>
>
>-- 
>Sarah Goslee
>http://www.functionaldiversity.org
>
>______________________________________________
>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