Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all punctuation from the end of a string

Tags:

java

string

regex

Examples:

// 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 String.replaceAll within endsWithRegex, we should be able to do something like this:

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

Any advice?

like image 676
budi Avatar asked Oct 23 '15 17:10

budi


People also ask

How do I remove all punctuation from a string?

One of the easiest ways to remove punctuation from a string in Python is to use the str. translate() method. The translate() method typically takes a translation table, which we'll do using the . maketrans() method.

How do I remove the punctuation at the end of a string in Java?

Try word = word. replaceAll("\\s*\\p{Punct}+\\s*$", ""); . It should remove all punctuation and will trim the string from the right.

How do you remove trailing punctuation in Python?

You do exactly what you mention in your question, you just str. strip it. str. strip can take multiple characters to remove.


1 Answers

I suggest using

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

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
like image 88
Wiktor Stribiżew Avatar answered Nov 11 '22 11:11

Wiktor Stribiżew