2

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.

5 Answers 5

2

If you replace your lineToReplace line by this:

String lineToReplace = "\\b" + oldLine + "(?!\\w)";

It should work the way you want.

  • By prefixing with \b we are making sure that there is a word boundary a the start.
  • By using negative lookahead (?!\w) we make sure that there is no word character on immediate right
Sign up to request clarification or add additional context in comments.

3 Comments

(?=\W|$) can also be written as (?!\w), or in this case just \B.
Thanks @Qtax: Updated the answer with simpler (?!\\w).
It can be more useful if you explain what your pattern does.
1

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

Comments

1
String input = "alma word1=\"word2\"";
String replacement = "word1=\"word3\"";
String output = input.replaceAll("\\bword1=\\\"word2\\\"", replaceMent);

3 Comments

Double quotes are nothing special in regex, so you don't need to escape them - ie "\\bword1=\"word2\"" is preferable
@jabal jabal ma yehezzak ri7 :D
@jabal Sorry about that, but I thought you knew Arabic, where jabal in Arabic means mountain, and there's a famous proverb that says: "Oh mountain, never be shaken against any wind" ;-)
1

You have word boundaries \b inside your string (the ") and you are using word boundaries in your regexp . Remove that last \b for example.

1 Comment

+1 for reminding me that I had a word boundaries \b inside my String already, which is the "
0

The only word boundary you need is at the front - the rest of your match already has word boundaries built in (the quotes etc).

This will work:

 cont.replaceAll("\\bword1=\"word2\"", "word1=\"word3\"");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.