Chit Khine Chit Khine - 1 month ago 5
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
@
or
#
. 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.

Answer

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

Comments