I can't for the life of me figure this out, even though it should be very simple.
How can I replace all occurrences of "("
and ")"
on a string with "\("
and "\)"
?
Nothing seems to work:
"foo ( bar ) foo".gsub("(", "\(") # => "foo ( bar ) foo"
"foo ( bar ) foo".gsub("(", "\\(") # => "foo \\( bar ) foo"
Any idea?
When using strings in Ruby, we sometimes need to put the quote we used to define the string inside the string itself. When we do, we can escape the quote character with a backslash \ symbol.
\n is the newline character. It prints a new line.
and \' is a special replacement pattern in Ruby. So what you want gsub to see is actually \\' , which can be produced by '\\\\\'' or "\\\\'" . Or, if you use the block form of gsub ( gsub("xxx") { "yyy" } ) then Ruby takes the replacement string "yyy" literally without trying to apply replacement patterns.
You already have the solution with your second attempt, you were just confused because the string is displayed in escaped form in the interactive interpreter. But really there is only one backslash there not two. Try printing it using puts and you will see that there is in fact only one backslash:
> "foo ( bar ) foo".gsub("(", "\\(")
=> "foo \\( bar ) foo"
> puts "foo ( bar ) foo".gsub("(", "\\(")
foo \( bar ) foo
If you need further convincing, try taking the length of the string:
> "foo ( bar ) foo".length
=> 15
> "foo ( bar ) foo".gsub("(", "\\(").length
=> 16
If it had added two backslashes it would print 17 not 16.
Here's what I just used to replace both parens in one call:
str.gsub(/(\(|\))/,'\\\\\1')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With