一旦在程序中定义了正则表达式,就可以使用 Pattern 和 Matcher 来使用正则表达式。
Pattern 对象是正则表达式编译后在内存中的表示形式,因此,正则表达式字符串必须先被编译为 Pattern 对象,然后再利用该 Pattern 对象创建对应的 Matcher 对象。执行匹配所涉及的状态保留在 Matcher 对象中,多个 Matcher 对象可共享同一个 Pattern 对象。
因此,典型的调用顺序如下:
Pattern p = Pattern.compile("a*b"); //使用 Pattern 对象创建 Matcher 对象 Matcher m = p.matcher("aaaab"); System.out.println(m.matches());//true m = p.matcher("aaaabb"); System.out.println(m.matches());//false
boolean b = Pattern.matches("a*b", "aaaaab")// true
b = Pattern.matches("a*b", "aaaaabb")// false
采用这种语句每次都要重新编译新的 Pattern 对象,不能重复利用已编译的 Pattern 对象,所以效率不高。
Pattern 是不可变类,可供多个并发线程安全使用。
Matcher 类提供了如下几个常用方法。
find():返回目标字段中是否包含与 Pattern 匹配的子串。
group():返回上一次与 Pattern 匹配的子串。
start():返回上一次与 Pattern 匹配的子串在目标字符串中的开始位置。
end():返回上一次与 Pattern 匹配的子串在目标字符串中的结束位置加 1。
lookingAt():返回目标字符串前面部分与 Pattern 是否匹配。
matches():返回整个目标字符串与 Pattern 是否匹配。
reset(),将现有的 Matcher 对象应用于一个新的字符序列。
public static void main(String[] arg){ String str = "你好,今天还有一个3个客户没有进行电话回访,分别是:" + "李先生:13212345678,王先生:13212345679,杨先生:155123456789"; //使用 Pattern 对象创建 Matcher 对象 Matcher m = Pattern.compile("(13\\d)\\d{8}") .matcher(str); //将符合正则表达式的子串输出 while(m.find()){ System.out.println("子串:" + m.group()); System.out.println("子串的开始位置:" + m.start()); System.out.println("子串的结束的位置:" + m.end()); } } 输出结果: 子串:13212345678 子串的开始位置:30 子串的结束的位置:41 子串:13212345679 子串的开始位置:46 子串的结束的位置:57matches() 和 lookingAt() 方法有点相似,只是 matches() 方法要求整个字符串和 Pattern 完全匹配时才返回 true,而 lookingAt() 只要字符串以 Pattern 开头就会返回 true。resent() 方法可将现有的 Matcher 对象应用于新的字符序列。
public static void main(String[] arg){ String[] strs = {"abc", "abcdef", "def"}; String regular = "[a-c]+"; Pattern p = Pattern.compile(regular); Matcher matcher = null; for(String r : strs){ if(matcher == null){ matcher = p.matcher(r); }else{ matcher.reset(r); } System.out.println(r + "__matches()__" + matcher.matches()); System.out.println(r + "__lookingAt()__" + matcher.lookingAt()); } } 输出结果 abc__matches()__true abc__lookingAt()__true abcdef__matches()__false abcdef__lookingAt()__true def__matches()__false def__lookingAt()__false
String 类里面也提供了 matches()方法,该方法返回该字符串是否匹配指定的正则表达式。例如:
"abc".matches("[a-c]+"); //true
除此之外,还可利用正则表达式对目标字符串进行分割、查找、替换等操作。如:
public static void main(String[] arg){ String[] strs = {"abc h_h", "abc def h_h", "def h_h"}; String regular = "([a-c]+|[d-f]+)"; Pattern p = Pattern.compile(regular); Matcher matcher = null; for(String r : strs){ if(matcher == null){ matcher = p.matcher(r); }else{ matcher.reset(r); } System.out.println(matcher.replaceAll("regular")); } } 输出结果 regular h_h regular regular h_h regular h_h