0

I'm trying to replace occurrences of special characters like /, :, etc in a string with */*, *:* respectively.

str.gsub!(/([;.\\/?:@&=+$,{}|^\[\]`<>#%"'])/, '*\1*')

However, I get a SyntaxError:

`@&' is not allowed as an instance variable name
syntax error, unexpected end-of-input, expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END
str.gsub!(/([;.\\/?:@&=+$,{}|^\[\]`<>#%"'])/, '*...
                     ^ (SyntaxError)

I tried to define that regexp as a string and use RegExp.quote(...) to convert it, but to no avail. Any suggestions would be highly appreciated!

1
  • 1
    You just forgot to escape the / symbol in the regex: str.gsub!(/([;.\\\/?:@&=+$,{}|^\[\]`<>#%"'])/, '*\1*'). RoR expects a valid variable name after @ in your case. Commented Feb 2, 2017 at 9:06

1 Answer 1

3

You just forgot to escape the / symbol in the regex:

str.gsub!(/([;.\\\/?:@&=+$,{}|^\[\]`<>#%"'])/, '*\1*')
                 ^

Else, a valid variable name after @ is expected.

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

1 Comment

I'd recommend reordering the escaped backslash and escaped-slash in the character-set for readability and easier comprehension.

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.