0

I have this string:

string_to_replace = 'if [ "${USER_CONFIG}" != "" ] ; then'

I want to get:

'Sample Only!!!!!'

I am doing:

string_to_replace.sub(/if [ "${USER_CONFIG}" != "" ] ; then/, 'Sample Only!!!!!')

But I do not get the desired result.

Is there a way to escape all regex characters at once in this string?

1
  • 1
    There is no point in using a regex if you replace literal strings. Regular expressions are good to use when the string you need to match is not known beforehand, but that follows some pattern that can be defined with regex. Commented Jan 4, 2017 at 8:53

2 Answers 2

2

Change this :

/if [ "${USER_CONFIG}" != "" ] ; then/

To this:

  1. 'if [ "${USER_CONFIG}" != "" ] ; then'

    or

  2. string_to_replace

    or

  3. /if \[ "\${USER_CONFIG}" != "" \] ; then/

    or

  4. "if \[ \"\${USER_CONFIG}\" != \"\" \] ; then"

in sub() function.

Sign up to request clarification or add additional context in comments.

5 Comments

thanks mate, that worked! Just would like to ask though why does it work? I would like to know if you know the reason why my first code doesn't work if you may. I am beginning ruby and I would like to expand my understanding on this topic.
[ ] and $ are special characters you need to escape them to get their literals. if you try /if \[ "\${USER_CONFIG}" != "" \] ; then/ this pattern will work.
Your 1, 2, and 4 all give a string, which is not what the OP was asking for. And your 3 gives what the OP was asking for, in a way that OP was most likely trying to avoid (OP wanted to do it "all at once"). Hence, it is not an answer to the question at all. However, this indirectly suggests what OP should have been doing.
@sawa don't be hypermetropic. Try to "see the trees for the forest !". If you find it is not a good answer for the question you can write another answer which include some functions for direct escaping.
@Meninx-メネンックス Here you go.
0

The real answer to the question as is is, yes, there is. And the way to do it is:

Regexp.new(Regexp.escape(string_to_replace))
#=> /if\ \[\ "\$\{USER_CONFIG\}"\ !=\ ""\ \]\ ;\ then/

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.