Replace blank spaces and semicolon in Java with Regex

Viewed 1215

I am trying to replace all strings that can contain any number of blank spaces followed by an ending ";", with just a ";" but I am confused because of the multiple blank spaces.

"ExampleString1            ;" -> "ExampleString1;"
"ExampleString2  ;" -> "ExampleString2;"
"ExampleString3     ;" -> "ExampleString3;"
"ExampleString1 ; ExampleString1 ;" -----> ExampleString1;ExampleString1

I have tried like this: example.replaceAll("\\s+",";") but the problem is that there can be multiple blank spaces and that confuses me

3 Answers

Try with this:

replaceAll("\\s+;", ";").replaceAll(";\\s+", ";")

Basically do a match to first find

(.+?) ->  anything in a non-greedy fashion
(\\s+) -> followed by any number of whitespaces
(;) -> followed by a ";"
$ -> end of the string

Than simply drop the second group (empty spaces), by simply taking the first and third one via $1$3

String test = "ExampleString1            ;"; 
test = test.replaceFirst("(.+?)(\\s+)(;)$", "$1$3");
System.out.println(test); // ExampleString1;

You just need to escape the meta character \s like this:

"ExampleString1   ;".replaceAll("\\s+;$", ";")
Related