Check if string is a punctuation character

后端 未结 6 1949
我寻月下人不归
我寻月下人不归 2020-12-03 21:13

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

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

In letter[3]

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 21:37

    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)
    

提交回复
热议问题