Trim leading or trailing characters from a string?

Brad Parks picture Brad Parks · Sep 5, 2014 · Viewed 81.7k times · Source

How can I trim the leading or trailing characters from a string in java?

For example, the slash character "/" - I'm not interested in spaces, and am looking to trim either leading or trailing characters at different times.

Answer

Reimeus picture Reimeus · Sep 5, 2014

You could use

Leading:

System.out.println("//test/me".replaceAll("^/+", ""));

Trailing:

System.out.println("//test/me//".replaceAll("/+$", ""));