Java String Handling RegEx

Remove multiple spaces from String in Java example

Remove multiple spaces from String in Java example shows how to remove multiple spaces from String in Java. Example also shows how to remove multiple spaces from String using regular expression and trim method.

How to remove multiple spaces from String in Java?

Sometimes string input contains multiple consecutive white spaces which we need to remove. Consider below given string inputs.

First string contains multiple spaces at the start of the string, second string element contains multiple spaces at the end of the string while third string element contains multiple spaces at start, in between and at the end of the string.

Multiple spaces can be matched with regular expression with “\\s+” pattern. “\\s” matches with any space character (i.e. space, tab, and new line character). “\\s+” matches one or more space characters.

Use replaceAll method which accepts regular expression to replace one or more space characters with the single space to remove multiple spaces from the String as given below.

Output

Our pattern removed multiple spaces from the middle of the string, but it still left single space at the start and end of the String. To remove that as well, use trim method along with replaceAll method as given below.

Output

Finally, if you are using Apache Commons library, you can use normalizeSpace method of StringUtils class to remove multiple spaces from the String as given below. normalizeSpace method first trims the string (thus removing all leading and trailing spaces from the string) and then it replaces multiple spaces with single space.

Output

Please let us know your views in the comments section below.

 

Join 1000+ fellow learners! Enter your email address below: