Sangram Mohite Sangram Mohite - 4 days ago 4
Java Question

Replace exact string with special characters and not the part of another substring

I am trying to replace the substring from a string like:

Sample string value '[1]T.1.v - Marriage Statement'!C10 and this

The text to replace is
'[1]T.1.v - Marriage Statement'!C10
with some other string say
so that the string becomes
Sample string value var1 and this
. The problem is there can be strings with values like
Sample string value '[1]T.1.v - Marriage Statement'!C101 and this
where the replacement should not work.
I was exploring the word boundary regex to limit the replacement:

String sample = "Value can be '[1]T.1.v - Marriage Statement'!C10 and this";
String a = sample.replaceAll("\\b'[1]T.1.v - Marriage Statement'!C10\\b", "var1");

But this doesn't seem to replace the word at all. I tried simple string replace but that will replace the substring in
Sample string value '[1]T.1.v - Marriage Statement'!C101 and this
as well giving output as
Sample string value var11 and this
which is an error.

Any suggestions how can this be achieved?


Remove leading \b then work with \Q...\E escape sequence to treat input string as literals:

String a = sample.replaceAll("\\Q" + param +"\\E\\b", "var1");