Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string is a punctuation character

Tags:

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");
    }
}
like image 505
sephtian Avatar asked Dec 18 '12 02:12

sephtian


People also ask

How do you check if a character in a string is punctuation?

IsPunctuation(String, Int32) Indicates whether the character at the specified position in a specified string is categorized as a punctuation mark.


2 Answers

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.

like image 90
Sergey Kalinichenko Avatar answered Sep 20 '22 14:09

Sergey Kalinichenko


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)
like image 23
Hans Brende Avatar answered Sep 20 '22 14:09

Hans Brende