user1044680
user1044680

Reputation: 91

How do I remove all punctuation that follows a single word in Java?

I need to remove punctuation following a word. For example, word?! should be changed to word and string: should be changed to string.

Edit: The algorithm should only remove punctuation at the end of the String. Any punctuation within the String should stay. For instance, doesn't; should become doesn't.

Upvotes: 5

Views: 12779

Answers (2)

wannik
wannik

Reputation: 12706

Use the method replaceAll(...) which accept a regular expression.

String s = "don't.  do' that! ";
s = s.replaceAll("(\\w+)\\p{Punct}(\\s|$)", "$1$2");
System.out.println(s);

Upvotes: 6

FailedDev
FailedDev

Reputation: 26930

You could use a regex to modify the string.

String resultString = subjectString.replaceAll("([a-z]+)[?:!.,;]*", "$1");

There are no "words" that I know of where ' is at the end and it is used as a punctuation. So this regex will work for you.

Upvotes: 2

Related Questions