-2

I have an input string which looks something like this.

String str="abc + abcd * abcde"

I wish to replace

abc with "xyz".

When I try replace function of string it replaces all the occurences of abc.

I should have the final string as

String str="xyz + abcd * abcde"

It is not necessary that "abc" will be first word in String.

I need to replace only that word which contains "abc" and not the one which contains "abcd". If I use "replace", it will replace all occurences of abc which is not required.

"abc" will have operator after abc. Something like this "abc+abcd+abcde"

Is there any elegant solution to this problem ?

10
  • Can you show your code? We cannot tell the problem without seeing your code Commented Jun 6, 2018 at 8:52
  • Try to generalize what the difference between the targeted abc is from the other occurrences... Commented Jun 6, 2018 at 8:53
  • 2
    you'll need to be more clear about your expectations. is it always the first "abc" you want to replace? is it every "abc" that is followed by a space? do you want to keep all instances of "abc" that are followed by another char? Commented Jun 6, 2018 at 8:54
  • 1
    str.replaceAll("\\b(abc)\\b", "xyz") Commented Jun 6, 2018 at 8:59
  • 1
    @f1sh first word in String, and first occurence of "abc" in String is not the same. Commented Jun 6, 2018 at 9:05

1 Answer 1

0

You can use the regex word boundary matcher \b for this:

str = str.replaceAll("\\babc\\b", "xyz");

See https://www.regular-expressions.info/wordboundaries.html

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

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.