本文已参与「新人创作礼」活动,一起开启掘金创作之路。
例如我们在开发中可能会遇到去除前后特殊字符的需求,如下
String str = ",this is txt," 我们可能只需要 this is txt . name如何快速得到我们想要的呢?
这个时候我们就需要用到 正则来去除
/**
*去掉字符串前后的指定字符
*/
public static String trimBothChars(String str, String splitter) {
String regex = "^" + splitter + "*|" + splitter + "*$";
return str.replaceAll(regex, "");
}
使用方式:
trimBothChars(字符串,指定要替换的字符)