众所周知JAVA有一个强大的工具包java.util.regex, 通过Pattern和 Matcher这两个类可以通过正则表达式来匹配字符串.
Pattern是正则表达式的编译后的对象形式,即正则模式.
Matcher是这个正则模式创建的匹配给定输入与此模式的匹配器.
典型的调用顺序是
String regex = "a*b";
Pattern p = Pattern.
Matcher m = p.
有了上面的匹配器对象m, 就可以通过m.matches()和m.find()方法判断"aaaaab"是否与正则regex 匹配.
这两个方法都可以判断是否匹配, 但是它们有什么区别呢?
1. 匹配方式不一样
matches() 是拿整个输入的字符串和定义的正则模式匹配;
find() 是包含匹配, 整个输入的字符串包含定义的正则模式.
上面的区别并不是这里我想说的, 我想说的是两个方法的调用顺序不一致, 结果也会不一致, 先看代码
@Test
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());亮了红灯.
接下来我把两个断言语句换了位置, 重新测试结果都能通过.
Why???
怀疑matcher0对象在调用matches()后肯定修改了这个对象的某个全局变量.
Debug进Matcher类的源码里面看一下, 果然发现在match()方法中有this.oldLast = this.last;等代码, 而find()中则没有.
这下就能解释了为什么调用顺序不一致结果也不一致, 除非不是同一个Matcher对象
@Test
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());
}
Pattern是正则表达式的编译后的对象形式,即正则模式.
Matcher是这个正则模式创建的匹配给定输入与此模式的匹配器.
典型的调用顺序是
String regex = "a*b";
Pattern p = Pattern.
compile
(regex
);
Matcher m = p.
matcher
("aaaaab");
有了上面的匹配器对象m, 就可以通过m.matches()和m.find()方法判断"aaaaab"是否与正则regex 匹配.
这两个方法都可以判断是否匹配, 但是它们有什么区别呢?
1. 匹配方式不一样
matches() 是拿整个输入的字符串和定义的正则模式匹配;
find() 是包含匹配, 整个输入的字符串包含定义的正则模式.
上面的区别并不是这里我想说的, 我想说的是两个方法的调用顺序不一致, 结果也会不一致, 先看代码
@Test
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());亮了红灯.
接下来我把两个断言语句换了位置, 重新测试结果都能通过.
Why???
怀疑matcher0对象在调用matches()后肯定修改了这个对象的某个全局变量.
Debug进Matcher类的源码里面看一下, 果然发现在match()方法中有this.oldLast = this.last;等代码, 而find()中则没有.
这下就能解释了为什么调用顺序不一致结果也不一致, 除非不是同一个Matcher对象
@Test
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());
}