1

I want to do two thing:

1) I want to create a character string with a double quote inside. An example in R would look like follows:

x <- 'vjghvbh"kljnj"kjbn"jk'
[1] "vjghvbh\"kljnj\"kjbn\"jk"

Question 1: How could I create such a character string without the backslash inside?

I tried to use gsub(), but unfortunately that didn't work. I also found some sources, which suggested cat(), but that just prints my character, but does not store it in x.

2) Let's assume that I solved Question 1. Then my character would look like follows:

[1] "vjghvbh"kljnj"kjbn"jk"

Now I need to find the positions of the double quotes. Based on this thread I tried gregexpr(). However, this also did not work, since I was not able to specify the pattern.

Question 2: How could I find the position of the double quotes within my character string?

The result in R should look like this:

[1] 8 14 19
Joachim Schork
  • 2,025
  • 3
  • 25
  • 48
  • 1
    Consider Q1 answered: `x <- 'vjghvbh"kljnj"kjbn"jk'` is correct and the string stored in `x` has no backslashes. `gregexpr('"', x, fixed=TRUE)[[1]]` will print the locations of matches. – Wiktor Stribiżew Jul 12 '17 at 20:24
  • Thanks for your answer Wiktor! If I run this code: `x <- 'vjghvbh"kljnj"kjbn"jk'` `x`, then the output is: `[1] "vjghvbh\"kljnj\"kjbn\"jk"`. Could you elaborate, why it has no backslashes in your opinion? – Joachim Schork Jul 12 '17 at 20:27
  • It is not my opinion, there are no backslashes. It is not WYSIWYG. To define a backslash in a *string literal*, you must use ``\\``. – Wiktor Stribiżew Jul 12 '17 at 20:28
  • Are there no backslashes shown, if you run that code? – Joachim Schork Jul 12 '17 at 20:30
  • `cat(x, sep="\n")` - no, no backslashes. Just what you need. See [**demo**](http://ideone.com/53kbQs). The question is a dupe. Lots of people are baffled by this. – Wiktor Stribiżew Jul 12 '17 at 20:31
  • 1
    Count the characters in `x`, then compare with the output of `nchar(x)`. – Rui Barradas Jul 12 '17 at 20:31
  • 1
    As for Q2, `gregexpr('\\"', x)`. – Rui Barradas Jul 12 '17 at 20:34
  • Thanks a lot @ Rui Barradas! That worked. Happy to give you credit if you formulate an answer! – Joachim Schork Jul 12 '17 at 20:35
  • 2 questions, 2 dupe reasons. You need no pattern for `gregexpr`, you only need a *string literal* denoting a fixed string, `'"'` or `"\""` with the `fixed=TRUE` argument. You just do not need to involve any regex engine here. – Wiktor Stribiżew Jul 12 '17 at 20:36
  • Of course it works, same as in my [**demo**](http://ideone.com/53kbQs) above. However, `'\\"'` is the same as `'"'` when used as a regex pattern because an escaped double quote is matching a double quote. Read the [***documentation***](https://stat.ethz.ch/R-manual/R-devel/library/base/html/grep.html). – Wiktor Stribiżew Jul 12 '17 at 20:39

0 Answers0