Reputation:
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
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
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
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