字符串匹配并替换Java

//正则表达式Pattern 、Matches


import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * Matcher类能对Pattern对象字符串进行匹配
 * @author Administrator
 *
 */
public class REF{
	public static void main(String[] args) {
		Pattern p=Pattern.compile("Indian");
		Matcher m=p.matcher("One little Indian,two little Indian,three little Indian");
		StringBuffer sb=new StringBuffer();
		boolean result = m.find();
		while(result){//如果匹配成功就替换
			m.appendReplacement(sb, "Chinese");
			result=m.find();//继续下一步匹配
		}
//		m.appendTail(sb);
		System.out.println(sb.toString());
	}
}
输出:One little Chinese,two little Chinese,three little Chinese

你可能感兴趣的:(Java)