JAVA正则表达式matcher中find,matches,lookingAt匹配字符串的区别

在Matcher类中find,matches,lookingAt都是匹配字符串的方法,这三个匹配操作方法均返回boolean类型,当匹配到时返回true,没匹配到则返回false,但容易混淆,整理它们的区别如下:

1,Matcher.matches()   对整个字符串进行匹配,只有整个字符串都匹配了才返回true 
2,Matcher.lookingAt()  从输入的头开始找,只有字符串的前缀满足模式才返回true
3,Matcher.find()  对字符串进行匹配,匹配到的字符串可以在任何位置. 

例子

1. 匹配字符串位置

public class MatcherTest {
    public static void main(String[] args){
        Pattern pattern = Pattern.compile("\\d{3,5}");
        String charSequence = "123-34345-234-00";
        Matcher matcher = pattern.matcher(charSequence);
 
        //虽然匹配失败,但由于charSequence里面的"123"和pattern是匹配的,所以下次的匹配从位置4开始
        print(matcher.matches());
        //测试匹配位置
        matcher.find();
        print(matcher.start());
 
        //使用reset方法重置匹配位置
        matcher.reset();
 
        //第一次find匹配以及匹配的目标和匹配的起始位置
        print(matcher.find());
        print(matcher.group()+" - "+matcher.start());
        //第二次find匹配以及匹配的目标和匹配的起始位置
        print(matcher.find());
        print(matcher.group()+" - "+matcher.start());
 
        //第一次lookingAt匹配以及匹配的目标和匹配的起始位置
        print(matcher.lookingAt());
        print(matcher.group()+" - "+matcher.start());
 
        //第二次lookingAt匹配以及匹配的目标和匹配的起始位置
        print(matcher.lookingAt());
        print(matcher.group()+" - "+matcher.start());
    }
    public static void print(Object o){
        System.out.println(o);
    }
}

执行结果:

false
true
- 0
true
- 4
true
- 0
true
- 0

2. 字符匹配

Pattern p = Pattern.compile(expression); // 正则表达式 
Matcher m = p.matcher(str); // 操作的字符串 
boolean b = m.matches(); //返回是否匹配的结果 
System.out.println(b); 

Pattern p = Pattern.compile(expression); // 正则表达式 
Matcher m = p.matcher(str); // 操作的字符串 
boolean b = m. lookingAt (); //返回是否匹配的结果 
System.out.println(b); 

Pattern p = Pattern.compile(expression); // 正则表达式 
Matcher m = p.matcher(str); // 操作的字符串 
boolean b = m..find (); //返回是否匹配的结果 
System.out.println(b); 

总结

1. matches是整个匹配,只有整个字符序列完全匹配成功,才返回True,否则返回False。但如果前部分匹配成功,将移动下次匹配的位置。lookingAt是部分匹配,总是从第一个字符进行匹配,匹配成功了不再继续匹配,匹配失败了,也不继续匹配。find是部分匹配,从当前位置开始匹配,找到一个匹配的子串,将移动下次匹配的位置。

2. Mathcher的find和lookingAt()方法执行成功之后,会影响后续的find的执行,因为下一次find会从上次匹配成功的位置开始继续查找,如果不想这样可以使用reset()方法复原匹配器的状态。