Trim characters in Java

How can I trim characters in Java?
e.g.

String j = “\joe\jill\”.Trim(new char[] {“\”});

j should be

"joe\jill"

String j = “jack\joe\jill\”.Trim("jack");

j should be

"\joe\jill\"

etc


Apache Commons has a great StringUtils class (org.apache.commons.lang.StringUtils). In StringUtils there is a strip(String, String) method that will do what you want.

I highly recommend using Apache Commons anyway, especially the Collections and Lang libraries.


This does what you want:

public static void main (String[] args) {
    String a = "\\joe\\jill\\";
    String b = a.replaceAll("\\\\$", "").replaceAll("^\\\\", "");
    System.out.println(b);
}

The $ is used to remove the sequence in the end of string. The ^ is used to remove in the beggining.

As an alternative, you can use the syntax:

String b = a.replaceAll("\\\\$|^\\\\", "");

The | means "or".

In case you want to trim other chars, just adapt the regex:

String b = a.replaceAll("y$|^x", ""); // will remove all the y from the end and x from the beggining