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.

1 Answer 1

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>")
Sign up to request clarification or add additional context in comments.

1 Comment

Yeap thats it, just change to s.replaceAll... not searchTerm.replaceAll

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.