Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove white space before punctuation in Java

Tags:

java

string

regex

I have a string

"This is a big sentence .  !  ?  !  but I have to remove the space ."   

In this sentence I want to remove all the space coming before the punctuation and should become

"This is a big sentence.!?!  but I have to remove the space."   

I am trying to use "\p{Punct}" but not able to replace in string.

like image 818
Arjit Avatar asked Dec 22 '22 10:12

Arjit


1 Answers

You should use positive lookahead:

newStr = str.replaceAll("\\s+(?=\\p{Punct})", "")

ideone.com demo for your particular string

Break down of the expression:

  • \s: White space...
  • (?=\\p{Punct}) ... which is followed by punctuation.
like image 68
aioobe Avatar answered Jan 03 '23 19:01

aioobe