正则表达式修剪
规范不明确,但可以使用正则表达式来做到这一点。
这是一个例子:
// trim digits from end
System.out.println(
"123a456z789".replaceAll("\\d+\\Z", "")
);
// 123a456z
// trim digits from beginning
System.out.println(
"123a456z789".replaceAll("\\A\\d+", "")
);
// a456z789
// trim digits from beginning and end
System.out.println(
"123a456z789".replaceAll("\\A\\d+|\\d+\\Z", "")
);
// a456z
锚点\A 和\Z 分别匹配输入的开头和结尾。 | 是替代品。 \d 是数字字符类的简写。 + 是“一个或多个”重复说明符。因此,模式\d+\Z 是“输入末尾的数字序列”的正则表达式。
参考文献
文字修整
如果您只想要文字后缀/前缀切割,则不需要正则表达式。这是一个例子:
public static String chopPrefix(String s, String prefix) {
if (s.startsWith(prefix)) {
return s.substring(prefix.length());
} else {
return s;
}
}
public static String chopSuffix(String s, String suffix) {
if (s.endsWith(suffix)) {
return s.substring(0, s.length() - suffix.length());
} else {
return s;
}
}
public static String chopPresuffix(String s, String presuffix) {
return chopSuffix(chopPrefix(s, presuffix), presuffix);
}
那么我们可以有:
System.out.println(
chopPrefix("abcdef", "abc")
); // def
System.out.println(
chopSuffix("abcdef", "ef")
); // abcd
System.out.println(
chopPresuffix("abcdef", "cd")
); // abcdef
System.out.println(
chopPresuffix("abracadabra", "abra")
); // cad