1

When I try this code below, it works fine using the regex boundaries:

"word john word".replaceAll("\\bjohn\\b","fill")

Result: "word fill word"

But if I need to search for a word that contains "#" it doesn't work:

"word john# word".replaceAll("\\john#\\b","fill")

Result: "word john# word"

How can I solve it?

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156

1 Answers1

1

She # symbol is not counted as a word character ([A-Za-z0-9_]), so your word boundary (\b) no longer matches.

You could use a positive lookahead and base yourself on the whitespace instead:

"word john# word".replaceAll("\\bjohn#(?=\\s+)","fill") // word fill word

Or use a non-word boundary (\B):

"word john# word".replaceAll("\\bjohn#\\B","fill") // word fill word

Or nothing at all:

"word john# word".replaceAll("\\bjohn#","fill") // word fill word
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • Thank you , I didn't know about the \\B and in my case I had to add an IF to check if the search string contains # and use \\B or \\b for each condition. – Jimmy Christyan Jun 19 '19 at 10:14