Check if string is a punctuation character

Depending on your needs, you could use either

Pattern.matches("\\p{Punct}", str)

or

Pattern.matches("\\p{IsPunctuation}", str)

The first pattern matches the following 32 characters: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

The second pattern matches a whopping 632 unicode characters, including, for example: «, », ¿, ¡, §, , , , , , and .

Interestingly, not all of the 32 characters matched by the first pattern are matched by the second. The second pattern does not match the following 9 characters: $, +, <, =, >, ^, `, |, and ~ (which the first pattern does match).

If you want to match for any character from either character set, you could do:

Pattern.matches("[\\p{Punct}\\p{IsPunctuation}]", str)

Here is one way to do it with regular expressions:

if (Pattern.matches("\\p{Punct}", str)) {
    ...
}

The \p{Punct} regular expression is a POSIX pattern representing a single punctuation character.


Do you want to check more punctuations other than just .?

If so you can do this.

String punctuations = ".,:;";//add all the punctuation marks you want.
...
if(punctuations.contains(letter[a]))