Check if string is a punctuation character

sephtian picture sephtian · Dec 18, 2012 · Viewed 56.2k times · Source

Let's say I have a String array that contains some letters and punctuation

String letter[] = {"a","b","c",".","a"};

In letter[3] we have "."

How can I check if a string is a punctuation character? We know that there are many possible punctuation characters (,.?! etc.)

My progress so far:

for (int a = 0; a < letter.length; a++) {
    if (letter[a].equals(".")) { //===>> i'm confused in this line
        System.out.println ("it's punctuation");
    } else {
        System.out.println ("just letter");
    }
}

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Dec 18, 2012

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.