在Java中,String有自己的查找与替换函数,但如果限制条件过多就会很难操作,使用正则表达式可以很好地对各种条件下的字符进行匹配和替换,从而功能更加强大,以下是利用正则表达式对字符串的查找与替换:
import java.util.regex.*;
import java.util.*;
public class TryRegex {
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
String regEx = "dog";
String str = "My dog hasn't got any nose.\nHow does your dog smell then?\nMy dog smells horrible.\n";
char[] marker = new char[str.length()];//定义相同长度的数组
Arrays.fill(marker, ' ');//用空格填充数组
Pattern pattern = Pattern.compile(regEx);//设置匹配的正则表达式
Matcher m = pattern.matcher(str);//利用匹配器进行匹配
StringBuffer newstr=new StringBuffer();
while (m.find()) {
m.appendReplacement(newstr, "goat");//先在匹配位置填充需要的字符串
}
m.appendTail(newstr);//再将不匹配的位置直接复制字符串
System.out.println("The origin is:\n"+str);
System.out.println("The final is:\n"+newstr);
}
}
实验结果如下: