JAVA 去除字符串首、尾特定字符
有时候在拼接字符串时候,某个拼接变量为空时,导致最后拼接的字符串首尾出现一个或多个分割符,为了拿掉首尾分割符,可以
使用如下正则方式:
public static String trimBothEndsChars(String srcStr, String splitter) {
String regex = "^" + splitter + "*|" + splitter + "*$";
return srcStr.replaceAll(regex, "");
}
测试:
test:
String str =";;6565;;65;;60004543;;"
String out = trimBothEndsChars(str, ";")
out:
6565;;65;;60004543
去除首
public static String trimBothEndsChars(String srcStr, String splitter) {
String regex = "^" + splitter + "*|";
return srcStr.replaceAll(regex, "");
}
测试:
test:
String str =";;6565;;65;;60004543;;"
String out = trimBothEndsChars(str, ";")
out:
6565;;65;;60004543;;