Reputation: 677
I'm making an app that searches a database - I want the search term to be bolded in my output. Suppose I have a string:
String s = "Foo Bar foobAr";
String searchTerm = "bar";
now, I want to surround every occurance of searchTerm in my string s with (to make it bold) regardless of case. Output should be:
"Foo <b>Bar</b> foo<b>bAr</b>"
This is relevant, but it makes the output the same as the searchTerm - I want to preserve the casing of the original string.
Upvotes: 2
Views: 104
Reputation: 7563
You can use back-referencing to replace the string you want. Take a look at this question for more explanations about back-referencing.
Taking that into account, this should do the trick:
s.replaceAll("(?i)(" + searchTerm + ")", "<b>$1</b>")
Upvotes: 2