Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gsub causing part of string to be substituted

Tags:

string

regex

ruby

I want to replace all occurrences of a single quote (') with backslash single quote (\'). I tried doing this with gsub, but I'm getting partial string duplication:

a = "abc 'def' ghi"
a.gsub("'", "\\'")
# => "abc def' ghidef ghi ghi"

Can someone explain why this happens and what a solution to this is?

like image 704
11th Hour Worker Avatar asked Feb 07 '23 23:02

11th Hour Worker


2 Answers

It happens because "\\'" has a special meaning when it occurs as the replacement argument of gsub, namely it means the post-match substring.

To do what you want, you can use a block:

a.gsub("'"){"\\'"}
# => "abc \\'def\\' ghi"

Notice that the backslash is escaped in the string inspection, so it appears as \\.

like image 74
sawa Avatar answered Feb 10 '23 15:02

sawa


Your "\\'" actually represents a literal \' because of the backslash escaping the next backslash. And that literal \' in Ruby regex is actually a special variable that interpolates to the part of the string that follows the matched portion. So here's what's happening.

abc 'def' ghi
    ^

The caret points to the first match, '. Replace it with everything to its right, i.e. def' ghi.

abc def' ghidef' ghi
    ++++++++

Now find the next match:

abc def' ghidef' ghi
               ^

Once again, replace the ' with everything to its right, i.e. ghi.

abc def' ghidef ghi ghi
               ++++
like image 41
slackwing Avatar answered Feb 10 '23 15:02

slackwing