budi budi - 4 months ago 55
Java Question

Regex Remove All Punctuation From End of String


// A B C. -> A B C
// !A B C! -> !A B C
// A? B?? C??? -> A? B?? C

Here's what I have so far:

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();

This current solution works, but since it's already calling
, we should be able to do something like this:

word = word.replaceAll(/* regex */, "");

Any advice?


I suggest using


It will match optional whitespace and punctuation at the end of the string.

If you do not care about the whitespace, just use \p{Punct}+$.

Do not forget that in Java strings, backslashes should be doubled to denote literal backslashes (that must be used as regex escape symbols).

Java demo

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