2013-10-03 36 views
3

做一个近期dzone益智游戏,用重复的数字字符串匹配,并通过我很困惑如下:混淆Groovy的正则表达式匹配

我希望下面的模式工作:/(\ d)\ 1/

当我使用操作员=〜(应该创建匹配器),此正确地匹配

if(!("${num}" =~ /(\d)\1/)) 
      println num 

不执行打印,例如,77,100,222,等等

但是当我使用==〜(suppos ED评估为布尔值),即:

if(!("${num}" ==~ /(\d)\1/)) 
      println num 

然后,它不会打印55,66,但它会打印100,111我必须改变模式/ \ d *(\ d)\ d \ d * /使其工作。

我误解了什么?为什么这种模式适用于=〜但不是==

任何洞察赞赏。

回答

3
=~ creates a matcher 
==~ (returns boolean, whether String matches the pattern) 

// =~ creates a Matcher, and in a boolean context, it's "true" if it has at least one 
//match, "false" otherwise. 
assert "cheesecheese" =~ "cheese" 

// ==~ tests, if String matches the pattern 
assert "2009" ==~ /\d+/ // returns TRUE 

documentation

+0

嗯,好吧,这是一个整串VS至少有一个匹配的东西......是有道理的,谢谢 – FOOM