Search code examples
javaregexstringreplaceall

Using String's ReplaceAll with regex


How to repalace the following String combination:
word1="word2"
With the following String combination:
word1="word3"

Using word boundaries \b.

I used the following, but did't work:

String word2 = "word2";
String word3 = "word3";
String oldLine = "word1=\"" + word2 + "\"";
String newLine = "word1=\"" + word3 + "\"";
String lineToReplace = "\\b" + oldLine + "\\b";
String changedCont = cont.replaceAll(lineToReplace, newLine);

Where cont is a String that contains a lot of characters including word1="word2" String combinations.


Solution

  • Remove the last \b. It will not do what you think, " is not a word character.