user2751130 user2751130 - 2 months ago 12x
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.


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?


strMain = strMain .replaceAll("(?i)(" + strSearchKeywords.replace(' ', '|') + ")",

Which means

strMain = strMain .replaceAll("(?i)(this|cont)",

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