I thought that I can use metacharacters such as \w to match word characters with one backslash. But for some reason, I need to include two backslashes.> grepl(pattern='\w', x="what")Error: '\w' is an unrecognized escape in character string starting "\w"> grepl(pattern='\\w', x="what")[1] TRUE I can't find the reason for this on the help pages. Does anyone know why? Thanks! [[alternative HTML version deleted]]
On 05/02/2013 12:49 PM, Seth Dickey wrote:> I thought that I can use metacharacters such as \w to match word characters > with one backslash. But for some reason, I need to include two backslashes. > > > grepl(pattern='\w', x="what") > Error: '\w' is an unrecognized escape in character string starting "\w" > > > grepl(pattern='\\w', x="what") > [1] TRUE > > I can't find the reason for this on the help pages. Does anyone know why?grepl wants a string containing a single backslash. R uses the backslash as an escape character, so you need to double it in your source, so the string ends up containing just one. "\w" is interpreted by R as an escaped w, which doesn't make sense. "\\w" is interpreted by R as a backslash followed by a w, and then the \w is interpreted by grepl the way you want. Duncan Murdoch
On Feb 5, 2013, at 9:49 AM, Seth Dickey wrote:> I thought that I can use metacharacters such as \w to match word characters > with one backslash. But for some reason, I need to include two backslashes. > >> grepl(pattern='\w', x="what") > Error: '\w' is an unrecognized escape in character string starting "\w" > >> grepl(pattern='\\w', x="what") > [1] TRUE > > I can't find the reason for this on the help pages. Does anyone know why?The help page for ?regex says near the top ... "Any metacharacter with special meaning may be quoted by preceding it with a backslash. The metacharacters in EREs are . \ | ( ) [ { ^ $ * + ?, but note that whether these have a special meaning depends on the context."> > Thanks! > > [[alternative HTML version deleted]] > > ______________________________________________ > 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.David Winsemius Alameda, CA, USA