4

I have a string I received from my DB, so in R it looks like:

a <- c("www", "x", "yes", "\303\243")

> a
[1] "www" "x"   "yes" "ã" 

What I want to do is to find which of the elements has backslash in it. I tried:

grepl('\\',a[4])

But I keep getting the error

invalid regular expression '\', reason 'Trailing backslash'

no matter whether I use cat or fixed=T.

How do I find that backslash in the list?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Yuval Zak
  • 41
  • 1
  • Have you seen http://stackoverflow.com/questions/11806501/backslash-in-r-string ? – lukeA Oct 19 '15 at 07:35
  • `a[4]` => `[1] "ã"` : R directly interprets \303 and \243 as the corresponding symbols – Cath Oct 19 '15 at 07:48
  • Maybe `Encoding(a) == "latin1"` ? – zx8754 Oct 19 '15 at 08:05
  • interesting, you arent allowed to search for that character. `as.integer(charToRaw("\\")); grepl("\092", a, useBytes=TRUE, fixed=TRUE)` is an error. – Rorschach Oct 19 '15 at 08:39
  • The simple truth is that there is no backslash in any element of `a`. Consider this string: `"Hello World!\n"`. Do you think there is a backslash in it? Furthermore, if you want to find backslash in a string with `grep`, you should: `grepl("\\\\",a[4])`, which is `FALSE` of course. – nicola Oct 19 '15 at 08:43

1 Answers1

0

You need to escape the backslash twice, once for the String literal in R and once for the regular Expression. grepl("\\", a[4]) applies the regexp \, while grepl("\\\\", a[4]) applies the regexp \\. To view the escaped string literal you can use cat("\\").

But i think your string does not contain any backslash at all, because in the definition the backslash occurs in an escape sequence, not as a character itself.

snaut
  • 2,261
  • 18
  • 37