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

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

Edit: The algorithm should only remove the punctuation marks at the end of the line. Any punctuation within the string must remain. For example, doesn't; must become doesn't .

+5
source share
2 answers

You can use regex to change the string.

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

There are no words that I know about where ' is at the end, and is used as punctuation. Therefore, this regular expression will work for you.

+2
source

Use the replaceAll(...) method, which accepts a regular expression.

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

Source: https://habr.com/ru/post/914773/


All Articles