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." 开发者_Go百科
I am trying to use "\p{Punct}"
but not able to replace in string.
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.
Try this regex to find all whitespace in front of punctuation: \s+(?=\p{Punct})
(Java String: "\\s+(?=\\p{Punct})"
)
You can use a group and reference it in the replacing string:
String text = "This is a big sentence . ! ? ! but I have to remove the space .";
String replaced = text.replaceAll("\\s+(\\p{Punct})", "$1")
Here we capture the punctuation in a group with (\\p{Punct})
and replace all the matched string with the group (named $1
).
Anyway, my answer is a mere curiosity: I think @aioobe answer is better :)
精彩评论