2

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.

Nic
  • 637
  • 2
  • 6
  • 19

1 Answers1

2

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>")
Kraylog
  • 7,383
  • 1
  • 24
  • 35