The below regex would match the non-word characters (except spaces) which must be followed by a space character or end of the line anchor. replaceAll
function helps to remove all the matched characters.
String s = "Blah! blah? blah... blah blah!!";
System.out.println(s.replaceAll("[^\\w\\s]+(?=\\s|$)", ""));
Output:
Blah blah blah blah blah
If you want to remove only ?
, .
, !
characters which was present at the last in a word, you could try the below code.
String s = "This is the f!!rst sentence! Is this the second one? The third sentence is here... And the fourth one!!";
System.out.println(s.replaceAll("[!?.]+(?=\\s|$)", ""));
Output:
This is the f!!rst sentence Is this the second one The third sentence is here And the fourth one