针对字符串大小写不确定,又需要进行匹配和替换的问题,有几种方法:
1、穷举法,即把输入的字符串按照大小写进行排列组合后,再去匹配和替换,这是最笨的方法,不过这是最直译的方法。
2、把要匹配的字符串和被匹配的文本都转成大写或者小写,再进行匹配和替换,这样作最简单,但是可能满足不了需求。
3、使用正则表达式,对要匹配的字符串作忽略大小写处理,如果匹配和替换都忽略大小写,可以直接用replaceAll,如果替换时还要考虑大小写,则用matcher.appendReplacement。
以下是简单的用法
String content = "begin Huawei and huawei and HUAWEI and huaWei and HuaWei and ZhongXin and zhongxin and ZHONGXIN and Zhongxin and ZhongXIN end"; String wordReg = "(?i)huawei";//用(?i)来忽略大小写 StringBuffer sb = new StringBuffer(); Matcher matcher = Pattern.compile(wordReg).matcher(content); while(matcher.find()){
matcher.appendReplacement(sb, "<font color='red'>"+matcher.group()+"</font>");//这样保证了原文的大小写没有发生变化 } matcher.appendTail(sb); content = sb.toString();
System.out.println(content);
//如果匹配和替换都忽略大小写,则可以用以下方法
content = content.replaceAll(wordReg,"<font color='red'>huawei</font>");
System.out.println(content);