I'm trying to make search keywords bold in result titles by replacing each keyword with <b>kw</b> using replaceAll() method. Also need to ignore any special characters in keywords for highlight. This is the code I'm using but it is double replacing the bold directive in second pass. I am looking for a elegant regex solution since my alternative is becoming too big without covering all cases. For example, with this input:
addHighLight("a b", "abacus")
...I get this result:
<<b>b</b>>a</<b>b</b>><b>b</b><<b>b</b>>a</<b>b</b>>cus
public static String addHighLight(String kw, String text) {
String highlighted = text;
if (kw != null && !kw.trim().isEmpty()) {
List<String> tokens = Arrays.asList(kw.split("[^\\p{L}\\p{N}]+"));
for(String token: tokens) {
try {
highlighted = highlighted.replaceAll("(?i)(" + token + ")", "<b>$1</b>");
} catch ( Exception e) {
e.printStackTrace();
}
}
}
return highlighted;
}