kzjfr0 kzjfr0 - 2 years ago 101
Java Question

How to remove only trailing spaces of a string in Java and keep leading spaces?


function removes both the trailing and leading space, however, if I only want to remove the trailing space of a string, how can I do it?


Answer Source

Using the regular expression \s+$, you can replace all trailing space characters (includes space and tab characters) with nothing ("").

final String text = "  foo   ";
System.out.println(text.replaceFirst("\\s+$", ""));

Here's a breakdown of the regex:

  • \s – any whitespace character
  • + – match one or more of the previous token; i.e., match one or more whitespace character
  • $ – the end of the string

Thus, the regular expression will match as much whitespace as it can that is followed directly by the end of the string: in other words, the trailing whitespace.

The investment into learning regular expressions will become more valuable, if you need to extend your requirements later on.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download