問題描述:最近在搭建一個開源平台網站,在做一個簡單搜索的功能,需要將搜索到的結果中被匹配的字符串添加不一樣的顏色,但是又不破壞被匹配的字符串。
使用的方法是替換被匹配的字符串加上font標簽。但是搜索出來的英文結果卻沒有那么理想。
原因分析:數據庫查詢使用like的時候是不區分大小寫的,而java替換字符串時是區分大小寫的,因此搜索出來的結果好多都沒有加上font標簽。
解決方法:使用強大的正則表達式。java中操作正則表達式的包為java.util.regex 包,主要由三個類所組成:Pattern、Matcher 和 PatternSyntaxException。
1、首先需要找到要被匹配的字符串,並且不區分大小寫
代碼:
1 Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); 2 Matcher matcher = pattern.matcher(str);
2、然后使用find方法,查找字符串的起始位置。
代碼:
1 while (matcher.find()) { 2 3 String match = str.substring(matcher.start() + len, matcher.end() 4 5 + len); 6 str = str.replaceFirst(match, "<font color='red'>" + match+ "</font>"); 7 len = len + s.length(); 8 }
最后的代碼:
package test2; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { /** * 不區分大小寫匹配字符串 * 並將被匹配字符串中的字符串加上一些東西 。 * 保持被匹配字符串中的字符串不變 * * @param args */ public static void main(String[] args) { String str = "Java JAva JAVA JavA"; String regex = "JAva"; //保存你要添加的html代碼的長度 int len = 0; String s = "<font color='red'></font>"; //不區分大小寫匹配字符串 Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(str); //循環查找,可能匹配到的不止一個字符串 while (matcher.find()) { //截取字符串,臨時保存匹配到的字符串 //起始位置和結束位置都要加一個len長度 String match = str.substring(matcher.start() + len, matcher.end() + len); //替換首次找到的字符串 str = str.replaceFirst(match, "<font color='red'>" + match + "</font>"); //len需要加上s長度 len = len + s.length(); } System.out.println(str); } }
程序運行結果:
<font color='red'>Java</font> <font color='red'>JAva</font> <font color='red'>JAVA</font> <font color='red'>JavA</font>
有什么更好的處理辦法請留言推薦,謝謝