You can use the group and refer to it in the replacement line:
String text = "This is a big sentence . ! ? ! but I have to remove the space ."; String replaced = text.replaceAll("\\s+(\\p{Punct})", "$1")
Here we fix the punctuation in the group with (\\p{Punct}) and replace the entire matched string with the group (named $1 ).
Anyway, my answer is just curiosity: I think @aioobe's answer is better :)
source share