gpt4 book ai didi

java - 删除字符串末尾的所有标点符号

转载 作者:搜寻专家 更新时间:2023-10-30 21:10:36 29 4
gpt4 key购买 nike

示例:

// 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 */, "");

有什么建议吗?

最佳答案

我建议使用

\s*\p{Punct}+\s*$

它将匹配字符串末尾的可选空格和标点符号。

如果您不关心空格,只需使用 \p{Punct}+$

不要忘记在 Java 字符串中,反斜杠应该加倍以表示文字反斜杠(必须用作正则表达式转义符号)。

Java demo

String word = "!Words word! ";
word = word.replaceAll("\\s*\\p{Punct}+\\s*$", "");
System.out.println(word); // => !Words word

关于java - 删除字符串末尾的所有标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33308203/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com