Trim leading or trailing characters from a string?
You can use Apache StringUtils.stripStart to trim leading characters, or StringUtils.stripEnd to trim trailing characters.
For example:
System.out.println(StringUtils.stripStart("//test/me", "/"));
will output:
test/me
Note that if for some reason you can't use the whole StringUtils library, you could just rip out the relevant parts, as detailed here:
You could use
Leading:
System.out.println("//test/me".replaceAll("^/+", ""));
Trailing:
System.out.println("//test/me//".replaceAll("/+$", ""));
For those using Spring:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/StringUtils.html#trimTrailingCharacter-java.lang.String-char-
import org.springframework.util.StringUtils;
public void setFileName(String fileName) {
// If the extension does not exist trim the trailing period
this.fileName = StringUtils.trimTrailingCharacter(fileName,'.');
}
Trim with Character, String, or Regex
If run-time is not a big issue for you, then this code will prove really helpful.
public class StringTrimmer {
public static String trim(String string, char ch){
return trim(string, ch, ch);
}
public static String trim(String string, char leadingChar, char trailingChar){
return string.replaceAll("^["+leadingChar+"]+|["+trailingChar+"]+$", "");
}
public static String trim(String string, String regex){
return trim(string, regex, regex);
}
public static String trim(String string, String leadingRegex, String trailingRegex){
return string.replaceAll("^("+leadingRegex+")+|("+trailingRegex+")+$", "");
}
// test
public static void main(String[] args) {
System.out.println(trim("110100", '1', '0')); // outputs: 01
System.out.println(trim("**Aa0*#**", '*')); // outputs: Aa0*#
System.out.println(trim("123##22222", "12", "22")); // outputs: 3##2
System.out.println(trim("101101##10101", "101")); // outputs: ##10
System.out.println(trim("123##abcde", "\\d", "[c-e]")); // outputs: ##ab
}
}