Dendrobates
Dendrobates

Reputation: 3534

Escape single quotation in vector of strings

I want to escape single quotation marks in a vector (for example to execute a SQL query), but I'm unable to do so.

Example code:

strings <- c("ef'gh")
strings2 <- gsub("'", "\'", strings)
cat(strings2)
print(strings2)

Expected output of either cat or print:

ef\'gh
"ef\'gh"

But none of the above. I tried multiple other combinations already, with different ways of escaping quotation, without success.

Upvotes: 1

Views: 30

Answers (1)

KoenV
KoenV

Reputation: 4283

You may use the following code:

strings <- c("ef'gh")
strings2 <- sub("\'", "\\\\'", strings)

cat(strings2)
  [1] ef\'gh
print(strings2)
  [1] "ef\\'gh"

Upvotes: 1

Related Questions