Java String Handling RegEx

Remove leading and trailing spaces from String in Java example

Remove leading and trailing spaces from String in Java example shows how to remove leading and trailing spaces from string using various approaches.

How to remove leading and trailing spaces from String in Java?

Consider below given String object which contains multiple spaces at start and end of the String.

Use trim method of String class to remove leading and trailing spaces from the String.

Output

Note:

trim method removes ‘\u0020’ which is a white space character. However, trim method does not remove Unicode white space character ‘\u00A0’. This character is commonly found in HTML in form of   (Unicode no break space). If you want to remove that, you can use replaceAll method of String class as given below.

How to remove only leading spaces from the String?

If you want to remove only leading spaces from the start of the String, trim method does not work as it will remove spaces from both the sides. You can use replaceAll┬ámethod along with the regular expression pattern to remove only leading spaces. Use “^\\s+” pattern to remove the leading spaces where,

Output

How to remove only trailing spaces from the String?

Use “\\s+$” pattern to remove only trailing spaces from the String where,

Output

Finally, if you are using Apache Commons library, you can use strip method of StringUtils class to remove white spaces from both ends of the String as given below.

Output

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

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.