Home » Android » java – Regex to remove spaces between numbers only

java – Regex to remove spaces between numbers only

Posted by: admin June 15, 2020 Leave a comment

Questions:

I need to remove the spaces between numbers only, so that a string like this:

"Hello 111 222 333 World!"

becomes

"Hello 111222333 World!"

I’ve tried this:

message = message.replaceAll("[\d+](\s+)[\d+]", "");

Doesn’t seem to get it done.

How to&Answers:

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.

Answer:

How about:

message = "Hello 111 222 333 World!".replaceAll("(\d)\s(\d)", "$1$2");

Gives:

"Hello 111222333 World!"