正则表达式-将搜索结果高亮
模拟:
将要查找的字符串中,指定字符替换为高亮的字符:
方法一:
package com.java.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class HighLight { public static void main(String[] args) { String keyword = "a"; String regexp = keyword + "+"; String name = "啊abfac是的Aaa爱的的a我要是alkja卡和户A玉玉aaa很快就asa啊发A阿达ff"; Pattern pattern = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(name); StringBuffer sb = new StringBuffer(); int start = 0; int end = 0; String temp = ""; while(matcher.find()){ start = matcher.start(); sb.append(name.substring(end, start)); temp = "<i class=\"highlight\">"+matcher.group()+"</i>"; sb.append(temp); end = matcher.end(); } sb.append(name.substring(end)); System.out.println(sb.toString()); } }
返回结果:
啊<i class="highlight">a</i>bf<i class="highlight">a</i>c是的<i class="highlight">Aaa</i>爱的的<i class="highlight">a</i>我要是<i class="highlight">a</i>lkj<i class="highlight">a</i>卡和户<i class="highlight">A</i>玉玉<i class="highlight">aaa</i>很快就<i class="highlight">a</i>s<i class="highlight">a</i>啊发<i class="highlight">A</i>阿达ff
方法二:
package com.java.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class HighLight2 { public static void main(String[] args) { String keyword = "a"; String regexp = keyword; String name = "啊abfac是的Aaa爱的的a我要是alkja卡和户A玉玉aaa很快就asa啊发A阿达ff"; Pattern pattern = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(name); String resp = matcher.replaceAll("<i class=\"highlight\">"+keyword+"</i>"); System.out.println(resp); } }
结果:
啊<i class="highlight">a</i>bf<i class="highlight">a</i>c是的<i class="highlight">a</i><i class="highlight">a</i><i class="highlight">a</i>爱的的<i class="highlight">a</i>我要是<i class="highlight">a</i>lkj<i class="highlight">a</i>卡和户<i class="highlight">a</i>玉玉<i class="highlight">a</i><i class="highlight">a</i><i class="highlight">a</i>很快就<i class="highlight">a</i>s<i class="highlight">a</i>啊发<i class="highlight">a</i>阿达ff
但是问题是,将name中的大写的A也替换为小写了。
方法三:
package com.java.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class HighLight3 { public static void main(String[] args) { String keyword = "a"; String regexp = keyword + "+"; String name = "啊abfac是的Aaa爱的的a我要是alkja卡和户A玉玉aaa很快就asa啊发A阿达ff"; Pattern pattern = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(name); StringBuffer sb = new StringBuffer(); while(matcher.find()){ matcher.appendReplacement(sb, "<i class=\"highlight\">"+matcher.group()+"</i>"); } matcher.appendTail(sb); System.out.println(sb.toString()); } }
结果:
啊<i class="highlight">a</i>bf<i class="highlight">a</i>c是的<i class="highlight">Aaa</i>爱的的<i class="highlight">a</i>我要是<i class="highlight">a</i>lkj<i class="highlight">a</i>卡和户<i class="highlight">A</i>玉玉<i class="highlight">aaa</i>很快就<i class="highlight">a</i>s<i class="highlight">a</i>啊发<i class="highlight">A</i>阿达ff
很nice。又简单又快捷
--------