Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

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.

like image 439
user1044680 Avatar asked Nov 13 '11 23:11

user1044680


2 Answers

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);
like image 160
wannik Avatar answered Sep 28 '22 06:09

wannik


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.

like image 33
FailedDev Avatar answered Sep 28 '22 08:09

FailedDev