1

I have the following text:

Testlalatest

I am trying to replace lala with another string,

Output should be Test[replace]test only if there is any char after or behind lala.

but I am getting that: Tes[replace]est

Code:

strLine = strLine.replaceAll("\\w"+word+"\\w", replaceWord);
1
  • 1
    Why are you using / instead of \ ? Commented Mar 12, 2015 at 7:56

2 Answers 2

4

You can use lookarounds to make sure your word is preceded and followed by a word character on each side.

strLine = strLine.replaceAll("(?<=\\w)" + word + "(?=\\w)", replaceWord);

Or else use \B on either side:

strLine = strLine.replaceAll("\\B" + word + "\\B", replaceWord);

RegEx Demo

Sign up to request clarification or add additional context in comments.

Comments

1

Working example:

public class Main {
    public static void main(String[] args) {
        for (String prefix : new String[] { "pre", "" }) {
            for (String suffix : new String[] { "suf", "" }) {
                String toReplace = "lala";
                String before = prefix + toReplace + suffix;
                System.out.println(before + " -> "
                        + before.replaceAll("(?<=.)" + toReplace
                        + "|" + toReplace + "(?=.)", "[replaced]"));
            }
        }
    }
}

Output:

prelalasuf -> pre[replaced]suf
prelala -> pre[replaced]
lalasuf -> [replaced]suf
lala -> lala

Information on the relevant regex syntax.

As was commented, it's strange that you've written //w instead of \\w for a word character. I'm not sure how that got replaced before.

Also, you said you wanted to match any char which means you want to use ., not \\w.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.