Escaping Apostrophes Using Gsub

Escaping Apostrophes Using Gsub

Someone else had this very issue, due to a special meaning/interpretation in Ruby's regex.

\' means $' which is everything after
the match. Escape the \ again and it
works

See this answer.

Does this work?

"this doesn't work".gsub /'/, '\\\\\'' => "this doesn\\'t work"

Ruby gsub doesn't escape single-quotes

\' means $' which is everything after the match.
Escape the \ again and it works

"Yaho'o".gsub("'", "\\\\'")

When trying to escape apostrophe with 'gsub', I get backreference

It is because "\\'" means the context following the match, which is "2".

R gsub a single double quotation mark

You do not need to escape a double quote in a regular expression. Just use "\"" or '"' to match a single double quote.

s = "Young Adult – 8-9\""
s
[1] "Young Adult – 8-9\""
gsub("\"", "", s)
[1] "Young Adult – 8-9"
gsub('"', "", s)
[1] "Young Adult – 8-9"

See this IDEONE demo

NOTE: Since you want to remove some literal text, you do not even need a regex, use fixed=TRUE argument to speed up the operation:

gsub('"', "", s, fixed=TRUE)

gsub and backslashes in R

It is a double quote, so either remove the quote and replace with blank

gsub('"',"", "c(\"Yes \", \" No\")", fixed = TRUE)
#[1] "c(Yes , No)"

or replace with a single quote

gsub('"',"'", "c(\"Yes \", \" No\")", fixed = TRUE)
#[1] "c('Yes ', ' No')"

If we print with cat, the character \ doesn't exist

cat("c(\"Yes \", \" No\")")
#c("Yes ", " No")

nchar('\"')
#[1] 1

cat('\"')
#"

how to replace an apostrophe using gsub

Try this out:

x.gsub(/[']/,"\\\\\'")

Result:

1.9.3p0 :014 > puts x.gsub(/[']/,"\\\\\'")
anupam\'s


Related Topics



Leave a reply



Submit