【发布时间】:2015-10-23 17:27:46
【问题描述】:
示例:
// 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*$", "");。它应该删除所有标点符号并从右侧修剪字符串。