I have a string with multiple white spaces in the beginning, middle and end:
" Humpty Dumpty sat "
.
I used regular expression (https://stackoverflow.com/a/2932439/13136767) to remove the extra whitespaces and replace it with group 1 (which is an empty space).
String str = " Humpty Dumpty sat ";
str = str.replaceAll("^ +| +$|( )+", "$1");
System.out.println("[" + str + "]");
Expected Output:
[ Humpty Dumpty sat ]
Actual Output:
[Humpty Dumpty sat]
A replacement string, is the text that each regular expression match is replaced with during a search-and-replace. The large whitespace at the beginning of the String should have been replaced by an empty space. Why did it not add an empty space, here, at the beginning of the String?