Chit Khine Chit Khine - 5 months ago 23
Java Question

How can we remove a ':' characters from a string?

I have strings like

@lle @mme: #crazy #upallnight:

I would like to remove the words which starts with either
. It works perfectly fine if those words doesn't contain the ':' character. However, that ':' character is left whenever I delete the words. Therefore I decided to replace those ':' characters before I delete the words using a string.replace() function. However, they are still not removed.

String example = "@lle @mme: #crazy #upallnight:";

example.replace(':',' ');

The result :
@lle @mme: #crazy #upallnight:

I am pretty stuck here, anyhelp would be appreciated.


You can do this:

example = example.replaceAll("[@#][^ ]+", "");

What this will do is replace any substrings in your string that match the regex pattern [@#][^ ]+ with the empty string. Since that pattern matches the words you want to dump, it'll do what you want.

Demo of the pattern on Regex101