我不是一个红宝石专家,可能这似乎是一个愚蠢的问题...但我太奇怪了(我认为)我在RSpec匹配器中找到了匹配.
你知道match
输入字符串或正则表达式.例:
"test".should match "test" #=> will pass
"test".should match /test/ #=> will pass
Run Code Online (Sandbox Code Playgroud)
当您在输入字符串中插入特殊的正则表达式字符时,奇怪的开始:
"*test*".should match "*test*" #=> will fail throwing a regex exception
Run Code Online (Sandbox Code Playgroud)
这意味着(我认为)输入字符串被解释为正则表达式,然后我应该转义特殊的正则表达式字符以使其工作:
"*test*".should match "\*test\*" #=> will fail with same exception
"*test*".should match /\*test\*/ #=> will pass
Run Code Online (Sandbox Code Playgroud)
从这个基本测试中,我理解match
将输入字符串视为正则表达式,但它不允许您转义特殊的正则表达式字符.
我是真的吗?这不是一种奇异的行为吗?我的意思是,这是一个字符串或正则表达式!
编辑后编辑:
继DigitalRoss(右)回答以下测试通过:
"*test*".should match "\\*test\\*" #=> pass
"*test*".should match '\*test\*' #=> pass
"*test*".should match /\*test\*/ #=> pass
Run Code Online (Sandbox Code Playgroud)
Dig*_*oss 12
你看到的是String vs Regexp中反斜杠转义字符的不同解释.在一个软(")引用的字符串中,\*
变为a *
,但/\*/
实际上是一个反斜杠后跟一个星.
如果对String对象使用硬引号(')或对反斜杠字符加倍(但仅对字符串使用),那么测试应该产生相同的结果.
归档时间: |
|
查看次数: |
16830 次 |
最近记录: |