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
Ruby on Rails Incompatible Library
Convert Hash Keys to Lowercase -- Ruby Beginner
How to Transpose Different Sized Ruby Arrays
How to Stop Rails' Built-In Server from Listening on 0.0.0.0 by Default
Cannot Assign Requested Address - Bind(2) (Errno::Eaddrnotavail)
Mismatched Bundler Version - Bundler 2, Ruby 2.6
Which Equality Test Does Ruby's Hash Use When Comparing Keys
Add a CSS Class to <%= F.Submit %>
Rails 3.1 - Changing Default Scaffold Views and Template
Best Way to Handle Dynamic CSS in a Rails App
Undefined Method 'Group_By_Day' - Rails 3.2
Ruby on Rails: How to Add a CSS File with Rails Project
Why a Module's Singleton Method Is Not Visible in Downstream Eigenclasses Where It Gets Mixed
How to Make a Class Whose Constructor Looks Like the Constructor of a Built-In Class
How to Convert Boolean Values to Integers
Why Does Rails 4.2 + Responders Keeps Telling Me to Add Responders to the Gemfile