正则表达式实现条件替换功能

Pattern px = Pattern.compile("java", Pattern.CASE_INSENSITIVE);
Matcher mx = px.matcher("java JAVA JavaJavaJAVA java llala jaVa");
System.out.println(mx.replaceAll("JAVA"));
mx.reset();


int cnt = 0;
StringBuffer sb = new StringBuffer();
while(mx.find()){
   if(++cnt % 2 == 1)
   mx.appendReplacement(sb, "java");
   else mx.appendReplacement(sb, "JAVA");
}
mx.appendTail(sb);
System.out.println(sb);

posted @ 2014-11-07 19:50  hjzqyx  阅读(573)  评论(0编辑  收藏  举报