Remove space before punctuation in Java

I have a line

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

In this sentence, I want to remove all spaces before punctuation and become

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

I am trying to use "\p{Punct}" but cannot replace it in a string.

+4
source share
3 answers

You should use a positive forecast :

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

ideone.com for your specific string

Expression gap:

  • \s : empty space ...
  • (?=\\p{Punct}) ... followed by punctuation.
+10
source

Try this regular expression to find all the spaces before the punctuation: \s+(?=\p{Punct}) (Java String: "\\s+(?=\\p{Punct})" )

+1
source

You can use the group and refer to it in the replacement line:

 String text = "This is a big sentence . ! ? ! but I have to remove the space ."; String replaced = text.replaceAll("\\s+(\\p{Punct})", "$1") 

Here we fix the punctuation in the group with (\\p{Punct}) and replace the entire matched string with the group (named $1 ).

Anyway, my answer is just curiosity: I think @aioobe's answer is better :)

0
source

All Articles