Regex to remove spaces between numbers only

You can use this lookaround based regex:

 String repl = "Hello 111 222 333 World!".replaceAll("(?<=\\d) +(?=\\d)", "");
 //=> Hello 111222333 World!

This regex "(?<=\\d) +(?=\\d)" makes sure to match space that are preceded and followed by a digit.

Leave a Comment