user2751130 user2751130 - 4 months ago 19
Java Question

Android partial string keyword match

In android, I have a main string and another string which has keyword(s) separated by space(s).
I want to output a string where the main string having matching keywords is highlighted.

Ex.

String strMain = "This string contains the main contents.";

String strSearchKeywords = "this cont";


The resulting output must be something like:

String strResult = "<b>This</b> string <b>cont</b>ains the main <b>cont</b>ents.";


One way is to split the search keywords into an array-list and then iterate through each of the items and highlight the main content.

However, is there any other way in one go without iterating, like using regex match?

Thanks.

Answer
strMain = strMain .replaceAll("(?i)(" + strSearchKeywords.replace(' ', '|') + ")",
        "<b>$1</b>"); 

Which means

strMain = strMain .replaceAll("(?i)(this|cont)",
        "<b>$1</b>");

The (?i) sets the ignore-case flag.