Best way to crop spaces in a row

How to adjust the gaps inside, leaving only one space for performance?

Input:
     AA     BB
Output:
AA BB

Input:
A      A
Output:
A A
+5
source share
5 answers
System.out.println("     AA     BB".replaceAll("\\s+", " ").trim());

Output:

AA BB

Note. Unlike some other solutions here, it also replaces one tab with one space. If you do not have tabs, you can use "{2,}", and this will be even faster:

System.out.println("     AA     BB".replaceAll(" {2,}", " ").trim());
+11
source

Replace two or more spaces "\\s{2,}"with one space " "and then execute trim()to get rid of the leading and trailing spaces, as shown in the first example.

output = input.replaceAll("\\s{2,}", " ").trim();
+7
source
s = s.replaceAll("\\s+", " " ).trim();
+2

"Hello a a g g a   gag gs    gs@".replaceAll( "[ ]+{2}", " ") ).trim();
0

, :

s = s.replaceAll("\\s+", " " ).trim();

But I think it’s also important to choose the right question. Instead of asking about cropping Stringusing regular expressions, why not just ask about cropping Stringand letting people respond to show you the best strategy?

There may be better ways to collapse places than using regex. Of course, there are other ways.

0
source

All Articles