3

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

xmlParser
  • 1,763
  • 3
  • 15
  • 40

3 Answers3

2

Try with this:

replaceAll("\\s+;", ";").replaceAll(";\\s+", ";")
Bambus
  • 1,403
  • 14
  • 26
1

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;
Eugene
  • 110,516
  • 12
  • 173
  • 277
0

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

"ExampleString1   ;".replaceAll("\\s+;$", ";")
Jason Webb
  • 7,758
  • 9
  • 39
  • 49
rzwitserloot
  • 65,603
  • 5
  • 38
  • 52