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

Since JDK 11

If you are on JDK 11 or higher you should probably be using stripTrailing().


Earlier JDK versions

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

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

Output

  foo

Online demo.

Here's a breakdown of the regex:

  • \s – any whitespace character,
  • ++ – match one or more of the previous token (possessively); i.e., match one or more whitespace character. The + pattern is used in its possessive form ++, which takes less time to detect the case when the pattern does not match.
  • $ – 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.

References

  • Java regular expression syntax

Another option is to use Apache Commons StringUtils, specifically StringUtils.stripEnd

String stripped = StringUtils.stripEnd("   my lousy string    "," ");