0

My goal is to replace a certain substring within a string that doesn't alter those that aren't strictly that substring. It is slightly confusing to write down so let me show you with an example.

Say I have the string

"StackOverflow Stack Overflow Stacks"

Now I would like to replace "Stack", if I am to use

x.replaceAll("Stack", "")

I will get

"Overflow  Overflow s"

which is not desired, instead I would like the following:

"StackOverflow Overflow Stacks"
1
  • 2
    There are a lot of good regex tutorials and examples in the net, what have you tried so far? Commented Jan 13, 2016 at 10:02

3 Answers 3

2

Use word boundaries:

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

Comments

2

Your requirement is not entirely clear.

You need to think about the conditions for "Stack" to be replaced.

A good example would be a word boundary: x.replaceAll("\\bStack\\b", "")

This will ensure that "Stack" surrounded by non-word characters will be replaced, while other instances of "Stack" will be left untouched.

You may want to be more specific and only replace when surrounded by whitespace:

  • x.replaceAll("(?<=\\s)Stack(?=\\s)", "") // replaces only "Stack"
  • x.replaceAll("\\sStack\\s", "") // also gets rid of the surrounding whitespace

Etc...

Comments

0

You can use word boundaries to accomplish this:

use the below code for the same:

String abc = "StackOverflow Stack Overflow Stacks";
abc = abc.replaceAll("\\bStack\\b", "");

System.out.println(abc);

The result is printed as StackOverflow Overflow Stacks

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.