santafebound santafebound - 11 days ago 4
Java Question

How can I replace a character and a word in a string with nothing?

String mGateway = "null,"
String mGateway2 = ",nullnull"
String mGateway3 = ",,,,null,"
mGateway.replaceAll("[null,]","");


For example, I want to replace all commas (,) and all words "null" with nothing. The output of
System.out.println(mGateway)
,
System.out.println(mGateway2)
and
System.out.println(mGateway3)
should all be blank.

Answer

To replace an exact word, use \\b in regex as in:

mGateway.replaceAll("\\bnull\\b|," , "");

So this replace null or , with an empty String (thus "").

Comments