This post will discuss how to remove punctuation from a String in Java.

The standard solution to remove punctuations from a String is using the replaceAll() method. It can remove each substring of the string that matches the given regular expression. You can use the POSIX character class \p{Punct} for creating a regular expression that finds punctuation characters.

Download  Run Code

 
The \p{Punct} class matches with the predefined punctuation character class: p{IsPunctuation}

Download  Run Code

 
If you need to remove all whitespaces along with the punctuation characters, you can use the following regex:

Download  Run Code

 
The \p{Punct} class matches with the US-ASCII punctuation by default, i.e., any one of these characters: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~. You can specify any additional characters that you want to remove by adding them in this regex.

Download  Run Code

 
If the regex is called frequently, you might want to compile it to get performance benefits. This can be done by creating a Pattern object.

Download  Run Code

That’s all about removing punctuation from a String in Java.