Reputation: 91
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
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
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