示例:
// A B C. -> A B C
// !A B C! -> !A B C
// A? B?? C??? -> A? B?? C
以下是我目前所拥有的:
while (endsWithRegex(word, "\\p{P}")) {
word = word.substring(0, word.length() - 1);
}
public static boolean endsWithRegex(String word, String regex) {
return word != null && !word.isEmpty() &&
word.substring(word.length() - 1).replaceAll(regex, "").isEmpty();
}
目前的解决方案可以工作,但由于它已经在endsWithRegex
中调用了String.replaceAll
,所以我们应该能够像这样做:
word = word.replaceAll(/* regex */, "");
有什么建议吗?
word = word.replaceAll("\\s*\\p{Punct}+\\s*$", "");
。它可以删除所有标点符号,并从右侧修剪字符串。 - Wiktor Stribiżew