user472557
user472557

Reputation:

Remove whole word only with Java

How can I remove the whole word on (not the substring on in the Confirmed) from the following string?

X-JP409 Confirmed on 13/2/12

Upvotes: 10

Views: 8992

Answers (4)

AlexR
AlexR

Reputation: 115378

There is special marker of word in regex: \b. So the better way is myString.replaceAll("\\bon\\b", "");

This works when word 'on' is in the beginning, end and in the middle of the text but only if it is a separate word. For example it will not remove "on" from word "one".

Upvotes: 10

adarshr
adarshr

Reputation: 62603

"X-JP409 Confirmed on 13/2/12".replace(" on ", " ");

String replace documentation

Upvotes: 3

Kleenestar
Kleenestar

Reputation: 799

If you want to replace all "on" which are not in a word, you can try to match the word boundary \b as well. Hope it helps.

    String abc = "on X-JP409 Confirmed on 13/2/12 on";
    abc = abc.replaceAll("\\bon\\b", "");
    System.out.println(abc);

or

    String abc = "on X-JP409 Confirmed on 13/2/12 on";
    abc = Pattern.compile("\\bon\\b").matcher(abc).replaceAll("");

replaceAll is actually invoking the Pattern api.

Upvotes: 8

PrimosK
PrimosK

Reputation: 13918

What about:

String str = "X-JP409 Confirmed on 13/2/12";
str.replaceAll(" on ", " ");

The output is what you are looking for:

X-JP409 Confirmed 13/2/12

Upvotes: 0

Related Questions