0

Let's say I have a string:

asd;;%$@#!G'{}[]

Now I want to escape special symbols:

;&|><*?`$(){}[]!#

So, the output will be something like:

asd\;\;%\$@\#\!G\'\{\}\[\]

How can I achieve this using gsub/sub in Ruby?

2
  • This is the regex for finding out special characters in a string. /[;\&\|><*\?`'\$(){}[]\!\#]/ Commented Apr 20, 2012 at 9:11
  • See stackoverflow.com/a/5396495/1315563 Commented Apr 20, 2012 at 9:16

2 Answers 2

1
test_value = "asd;;%$@#!G'{}[]"
SPEC_REGEXP = /((;)|(\&)|(\|)|(>)|(<)|(\*)(\?)|(`)|(\$)|(\()|(\))|({)|(})|(\[)|(\])|(!)|(#))/
test_value.gsub!(SPEC_REGEXP,'\\\\\1')
Sign up to request clarification or add additional context in comments.

Comments

1

Here's pretty much the same idea as in soundar's solution (but using character classes and no capturing):

"asd;;%$@#!G'{}[]".gsub(/[;&|><*?`$(){}\[\]!#]/, '\\\\\\0')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.