Pattern和Matcher概述
什么是Pattern
正则表达式的编译表示形式。
什么是Matcher
通过解释 Pattern 对 character sequence 执行匹配操作的引擎
Pattern调用顺序
Pattern p = Pattern.compile(“a*b”);
Matcher m = p.matcher(“aaaaab”);
boolean b = m.matches();
方法介绍
Pattern.compile(); 将给定的正则表达式编译到模式中
Pattern.matcher(); 创建匹配给定输入与此模式的匹配器
Matcher find() 在匹配器中查找满足正则表达式的字符串,找到返回true
Matcher group() 返回在匹配器查找到的字符串
演示:
public class PattermAndMatcher {
public static void main(String[] args) {
String s = "aaaab";
String regex = "a*b";
Pattern p = Pattern.compile(regex); //获取正则表达式
Matcher m = p.matcher(s); //获取匹配器
boolean b = m.matches(); //看是否能匹配,匹配返回true
System.out.println(b);
}
}
练习:
描述:把一个字符串中的手机号获取出来
public class PattermAndMatcher {
public static void main(String[] args) {
String s = "我的手机号码是18988888888,曾经用过18987654321,还用过18812345678";
String regex = "1[3578]\\d{9}"; //手机号码的正则表达式
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
while (m.find()) { //查找满足正则表达式的手机号,找到返回true
String s1 = m.group(); //返回查找到的手机号
System.out.println(s1);
}
}
}