Pattern,可以将其看作某个操作规则的编译对象,即编译过的正则表达式,使用它可按指定的规则来处理相应的字符。
Matcher,是对字符按指定的规则进行匹配查找的工具。
举一个通俗的例子,有一大堆水果,其中有苹果和梨,香蕉等等。有告诉你去找苹果,其中Pattern就相于[苹果]的封装,这是规则。然后你用相机给苹果照了个照,然后拿着相片去水果里比对进行匹配,这个相片就相当于matcher。
做一个简单的测试,来熟悉了解Pattern,Matcher类以及它们相应方法含义:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Patterntest {
private static String TEST = "Kelvin Li and Kelvin Chan are both working in Kelvin Chen's KelvinSoftShop company";
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Pattern pattern = Pattern.compile("Kelvin");
Matcher matcher = pattern.matcher(TEST);
StringBuffer sb = new StringBuffer();
boolean result = matcher.find();
while (result) {
matcher.appendReplacement(sb, "Kevin");// this operation will replace the matched strings with you provide when the pattern is met.
result = matcher.find();
}
matcher.appendTail(sb);//app the the rest of strings after the match work done.
System.out.println("the final result is : " + sb.toString());
}
}原文地址:http://blog.csdn.net/a2758963/article/details/6967578