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.
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).
replaceAll("[\\d+](\\s+)[\\d+]", "");
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.
How about:
message = "Hello 111 222 333 World!".replaceAll("(\\d)\\s(\\d)", "$1$2");
Gives:
"Hello 111222333 World!"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With