Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to remove spaces between numbers only

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.

like image 231
Badr Ghatasheh Avatar asked May 09 '14 09:05

Badr Ghatasheh


People also ask

How do you stop a space in regex?

You can easily trim unnecessary whitespace from the start and the end of a string or the lines in a text file by doing a regex search-and-replace. Search for ^[ \t]+ and replace with nothing to delete leading whitespace (spaces and tabs).

How do I remove spaces between numbers in Java?

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

How do I get rid of white space in regex?

The replaceAll() method accepts a string and a regular expression replaces the matched characters with the given string. To remove all the white spaces from an input string, invoke the replaceAll() method on it bypassing the above mentioned regular expression and an empty string as inputs.


2 Answers

How about:

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

Gives:

"Hello 111222333 World!"
like image 44
Lee F Avatar answered Sep 28 '22 03:09

Lee F


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.

like image 191
anubhava Avatar answered Sep 28 '22 01:09

anubhava