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,903
  • 4
  • 19
  • 48

3 Answers3

2

Try with this:

replaceAll("\\s+;", ";").replaceAll(";\\s+", ";")
Bambus
  • 1,493
  • 1
  • 15
  • 32
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
  • 117,005
  • 15
  • 201
  • 306
0

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

"ExampleString1   ;".replaceAll("\\s+;$", ";")
Jason Webb
  • 7,938
  • 9
  • 40
  • 49
rzwitserloot
  • 85,357
  • 5
  • 51
  • 72