我上一篇写了正则表达式的总结,这一篇讲一下Java中Pattern和Matcher类的使用。java
正则表达式总结请移步:【正则表达式】(0)总结web
Pattern :正则表达式的编译表示形式。正则表达式
主要就是用来写正则表达式。
svg
public final class Patternextends Object implements Serializable
Matcher 经过解释 Pattern 对 character sequence 执行匹配操做的引擎。spa
看名字也知道了,匹配器主要用来匹配。
.net
public final class Matcher extends Object implements MatchResult
int caseInsensitive = Pattern.CASE_INSENSITIVE; // 忽视大小写,使用Pattern的compile(String regex, int flags) 方法时使用。
Pattern类和Matcher类都没有构造器。code
Pattern类有静态方法,直接调用静态方法便可。xml
Matcher对象是经过Pattern类的matcher(CharSequence input) 进行建立的。能够看下面 3.5建立匹配器对象
将给定的正则表达式编译到模式中。blog
private static Pattern c = Pattern.compile("[a-z]+"); // 建立正则表达式编译到模式中
将给定的正则表达式编译到具备给定标志的模式中。
private static Pattern c = Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE);
返回匹配器的字符串表示形式。
/** 在使用正则表达式时,利用好其预编译功能,能够有效加快正则匹配速度 */ private static Pattern p = Pattern.compile("[a-z]+"); public static void main(String[] args) { String s = p.toString(); System.out.println(s); // [a-z]+ }
编译给定正则表达式并尝试将给定输入与其匹配。
boolean m = Pattern.matches("[a-z]+", "hello"); System.out.println(m); // true boolean m2 = Pattern.matches("[a-z]+", "123"); System.out.println(m2); // false
建立匹配给定输入与此模式的匹配器。
/** 在使用正则表达式时,利用好其预编译功能,能够有效加快正则匹配速度 */ private static Pattern p = Pattern.compile("[a-z]+"); public static void main(String[] args) { Matcher hello = p.matcher("hello"); // 获取到一个匹配器 }
尝试将整个区域与模式匹配。
/** 在使用正则表达式时,利用好其预编译功能,能够有效加快正则匹配速度 */ private static Pattern p = Pattern.compile("[a-z]+"); public static void main(String[] args) { Matcher matcher = p.matcher("hello"); boolean m = matcher.matches(); System.out.println(m); // true Matcher matcher2 = p.matcher("hello 123"); boolean m2 = matcher2.matches(); System.out.println(m2); // false }
返回此匹配器模式中的捕获组数。
private static Pattern p = Pattern.compile("(([a-z]).)"); public static void main(String[] args) { Matcher matcher = p.matcher("a-b-c-d-e-"); int count = matcher.groupCount(); System.out.println(count); }
private static Pattern p = Pattern.compile("(([a-z]).)"); public static void main(String[] args) { Matcher matcher = p.matcher("a-b-c-d-e-"); String s = matcher.replaceFirst("z-"); // 替换第一个匹配的字符串 System.out.println(s); // z-b-c-d-e- String all = matcher.replaceAll("z-"); // 替换全部匹配的字符串 System.out.println(all); // z-z-z-z-z- }
尝试查找与该模式匹配的输入序列的下一个子序列。
返回由之前匹配操做所匹配的输入子序列。
/** 在使用正则表达式时,利用好其预编译功能,能够有效加快正则匹配速度 */ private static Pattern p = Pattern.compile("[a-z]."); public static void main(String[] args) { Matcher matcher = p.matcher("a-b-c-d-e-"); // 一个个匹配 boolean f = matcher.find(); String g = matcher.group(); System.out.println("是否有匹配的子字符串:"+f+"\n匹配的结果为:"+g); // 循环匹配 while (matcher.find()) { String group = matcher.group(); System.out.println(group); } }