匹配方式不一样 
matches() 是拿整个输入的字符串和定义的正则模式匹配; 
find() 是包含匹配, 整个输入的字符串包含定义的正则模式. 
调用顺序不一致, 结果也会不一致 
-  public void testRegex()
 
 -     {
 
 -         String str0 = "I want to train 'xxx' to 'yyy'"; 
 
 -         Matcher matcher0 = pattern0.matcher(str0);
 
 -    
 
 -         assertTrue(matcher0.matches());
 
 -         assertTrue(matcher0.find());
 
 -     }
 
 
  复制代码 
我期望这个单元测试肯定能一路绿灯, 结果assertTrue(matcher0.find());亮了红灯. 
接下来我把两个断言语句换了位置, 重新测试结果都能通过.为什么呢??? 
怀疑matcher0对象在调用matches()后肯定修改了这个对象的某个全局变量. 
Debug进Matcher类的源码里面看一下, 果然发现在match()方法中有this.oldLast = this.last;等代码, 而find()中则没有. 
这下就能解释了为什么调用顺序不一致结果也不一致, 除非不是同一个Matcher对象 
-     public void testRegex()
 
 -     {
 
 -         String str0 = "I want to train 'xxx' to 'yyy'"; 
 
 -         Matcher matcher0 = pattern0.matcher(str0);
 
 -         Matcher matcher1 = pattern0.matcher(str0);
 
 -         assertTrue(matcher0.matches());
 
 -         assertTrue(matcher1 .find());
 
 -     }
 
  复制代码 |