16

I'm not a ruby expert and may be this will seem a silly question...but I'm too courious about an oddity (I think) I've found in RSpec matcher called match.

You know match takes in input a string or a regex. Example:

"test".should match "test" #=> will pass
"test".should match /test/ #=> will pass

The strange begins when you insert special regex characters in the input string:

"*test*".should match "*test*" #=> will fail throwing a regex exception

This means (I thought) that input strings are interpreted as regex, then I should escape special regex characters to make it works:

"*test*".should match "\*test\*" #=> will fail with same exception
"*test*".should match /\*test\*/ #=> will pass

From this basic test, I understand that match treats input strings as regular expressions but it does not allow you to escape special regex characters.

Am I true? Is not this a singular behavior? I mean, it's a string or a regex!


EDIT AFTER ANSWER:

Following DigitalRoss (right) answer the following tests passed:

"*test*".should match "\\*test\\*" #=> pass
"*test*".should match '\*test\*' #=> pass
"*test*".should match /\*test\*/ #=> pass

1 Answer 1

13

What you are seeing is the different interpretation of backslash-escaped characters in String vs Regexp. In a soft (") quoted string, \* becomes a *, but /\*/ is really a backslash followed by a star.

If you use hard quotes (') for the String objects or double the backslash characters (only for the Strings, though) then your tests should produce the same results.

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

3 Comments

Thanks you are right. I edited the question with the code tests you mentioned.
You can also escape regexp like strings, e.g. %r{\*test\*} Not so useful with this because you still need backslashes, but found it invaluable when matching for /
lightly related, but i ran into a similar issue - mine was around string comparisons containing escaped characters, `\nsome text\n' for example. fixed using double quotes to prevent rspec from double escaping.

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.