Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...