我不是 Ruby 专家,可能这个问题看起来很傻...但我对 RSpec 匹配器叫做 match 发现了一个奇怪的事情(我认为)。
你知道 match
接受一个字符串或正则表达式作为输入。例如:
"test".should match "test" #=> will pass
"test".should match /test/ #=> will pass
当您在输入字符串中插入特殊的正则表达式字符时,情况就变得奇怪了:
"*test*".should match "*test*" #=> will fail throwing a regex exception
这意味着(我认为)输入的字符串被解释为正则表达式,因此我应该转义特殊的正则表达式字符以使其起作用:
"*test*".should match "\*test\*" #=> will fail with same exception
"*test*".should match /\*test\*/ #=> will pass
从这个基本的测试中,我理解到match
将输入字符串视为正则表达式,但它不允许您转义特殊的正则表达式字符。
我说的对吗?这不是一种奇怪的行为吗?我的意思是,这是一个字符串还是一个正则表达式!
回答后编辑:
根据DigitalRoss(正确)的答案,以下测试已通过:
"*test*".should match "\\*test\\*" #=> pass
"*test*".should match '\*test\*' #=> pass
"*test*".should match /\*test\*/ #=> pass