How do I trim spaces inside leaving only one space taking consideration of performance?
Input: AA BB Output: AA BB Input: A A Output: A A
How do I trim spaces inside leaving only one space taking consideration of performance?
Input: AA BB Output: AA BB Input: A A Output: A A
Replace two or more spaces "\\s{2,}" by a single space " " and do a trim() afterwards to get rid of the leading and trailing spaces as you showed in the 1st example.
output = input.replaceAll("\\s{2,}", " ").trim();
System.out.println(" AA BB".replaceAll("\\s+", " ").trim());
Output:
AA BB
Note: Unlike some of the other solutions here, this also replaces a single tab with a single space. If you don't have any tabs you can use " {2,}" instead which will be even faster:
System.out.println(" AA BB".replaceAll(" {2,}", " ").trim());
There are correct answers here, e.g.:
s = s.replaceAll("\\s+", " " ).trim();
But I think it's also important to choose the correct question. Instead of asking about trimming a String using regular expressions, why not just ask about trimming the String, and allow people answering to show you the best strategy?
There may well be better ways to collapse spaces than to use a regular expression. There are certainly other ways.