Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Escape Parenthesis

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?

like image 555
Todd Horrtyz Avatar asked May 06 '10 18:05

Todd Horrtyz


People also ask

How do you escape special characters in Ruby?

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.

How do you make a new line in Ruby?

\n is the newline character. It prints a new line.

How do you add a backslash to a string in Ruby?

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.


2 Answers

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.

like image 197
Mark Byers Avatar answered Sep 24 '22 01:09

Mark Byers


Here's what I just used to replace both parens in one call:

str.gsub(/(\(|\))/,'\\\\\1')
like image 36
Pål Brattberg Avatar answered Sep 26 '22 01:09

Pål Brattberg