天天看点

Java-Pattern和Matcher一、Pattern二、Matcher

一、Pattern

有经验的小伙伴们肯定知道,我们的字符串提供了matches(reg)方法用来判断该字符串是否满足正则表达式,而Pattern只是创建了一个正则表达式,那么为什么选择用Pattern而不是字符串的matches呢

1.1使用Pattern的原因

因为字符串提供的matches方法,我们每调用一次它就会自动创建一个相同的pattern,这样的做法效率是很低的,我们何不主动创建一个pattern,然后每次需要匹配就直接用它而不需要再次创建,大大提高了程序的效率。

1.2 Pattern的用法

/**
在开发中,pattern常常是和Matcher配合使用的
Pattern最常用的方法就是compile,我们只需要记住它就好了
**/
Pattern p = Pattern.compile("\\d{3}-\\d{8}") #一个简单的电话匹配

           

二、Matcher

2.1 Matcher的创建

Matcher的构造方法是私有的,我们一般通过调用Pattern对象的matcher方法返回一个matcher。

String info = "名字:wulei  sda地址:hunan 电话:010-82350555";
Pattern p = Pattern.compile("(名字:\\w+\\s+)|(地址:\\w+\\s+)|(电话:\\d{3}-\\d{8})");
Matcher matcher = p.matcher(info);
           

2.2 Matcher的匹配方式

Matcher对象提供了三个不同的匹配方式:matches、 lookingAt()、find()。三个方法均返回boolean类型,当匹配到时返回true,没匹配到则返回false
  1. matches:要求整个字符串必须符合正则表达式,否则返回false。
    String info = "123abc";
    Pattern p = Pattern.compile("\\d+");
    Pattern p1 = Pattern.compile("\\d+\\w+");
    Matcher matcher = p.matcher(info);
    Matcher matcher1 = p1.matcher(info);
    
    System.out.println(matcher.matches());//false
    System.out.println(matcher1.matches());//true
               
  2. lookingAt():要求该字符串的开头符合使用的正则。
    System.out.println(matcher.lookingAt()); //true
               
  3. find():寻找该字符串中下一个符合正则表达的子串。每次调用它,matcher里面的匹配指针都会向后移。
    String info = "123abc456def789";
    Pattern p = Pattern.compile("\\d+");
    Matcher matcher = p.matcher(info);
    while(matcher.find()){
        System.out.println(matcher.group());
    }
    输出:
    123
    456
    789
               

4.reset():重置find()的指针。

注意:lookingAt()会影响到find()查找的子字符串

String info = "123abc456def789";
Pattern p = Pattern.compile("\\d+");
Matcher matcher = p.matcher(info);
System.out.println("执行lookingAt()后的group:");
matcher.lookingAt();
System.out.println(matcher.group());
System.out.println("执行find():");
while(matcher.find()){
    System.out.println(matcher.group());
}

输出:
执行lookingAt()后的group:
123
执行find():
456
789
           

2.2 Matcher获取匹配到的信息

当我们执行完匹配操作后,我们常常需要获得匹配到的具体字符串。matcher对象能够使用group()、start()、end()方法来获取相关信息。
  1. start():返回匹配到的子字符串在字符串中的索引位置.
  2. end():返回匹配到的子字符串的最后一个字符在字符串中的索引位置+1
  3. group():返回匹配到的子字符串

注意:这三个方法是基于我们matcher执行matches()|lookingAt()|find()并匹配成功的情况下才能使用,否则会报错

此外,这三个方法还有对应的重载方法,start(int index)、end(int index)、group(int index)

  • group(index):返回匹配到的子字符串里的第index个分组,group(0)=group()。
  • start(index):返回匹配到的子字符串里的第index个分组开始的索引。
  • end(index):返回匹配到的子字符串里的第index个分组结束的索引+1。
String info = "123abc456def789";
Pattern p = Pattern.compile("(\\d+)([a-z]+)");
Matcher matcher = p.matcher(info);

while (matcher.find()){
    System.out.println("start(1): " + matcher.start(1));
	System.out.println("start(2): " + matcher.start(2));
	System.out.println("end(1): " + matcher.end(1));
	System.out.println("end(2): " + matcher.end(2));
}

输出:
start(1): 0
start(2): 3
end(1): 3
end(2): 6
start(1): 6
start(2): 9
end(1): 9
end(2): 12