1

I have a variable String that should be replaced, when the String is matched as a whole at word boundaries. The variable String might contain any special characters, at any position.

I had some success with this regex:

\b\QExample String to replace\E

or implemented in Kotlin:

string.replace("""\b${Regex.escape(toReplace)}""".toRegex(), replacement)

However, this does not work when toReplace is something like [template] Example String to replace.

I guess that the reason for this is, that [ is not seen as a "word" and therefore does not match by the \b. Is there a way to replace this String and be as flexible as possible with the inputs?

Marcel Bochtler
  • 1,159
  • 1
  • 12
  • 21

1 Answers1

1

You could use a whitespace boundary:

(?<!\S)\[template\] Example String to replace

Full Kotlin code:

string.replace("""(?<!\S)${Regex.escape(toReplace)}""".toRegex(), replacement)
Tim Biegeleisen
  • 451,927
  • 24
  • 239
  • 318