20

假设我有一个包含一些字母和标点符号的字符串数组

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

在字母[3]中,我们有“。”

如何检查字符串是否为标点符号?我们知道有很多可能的标点符号(,.?! 等)

到目前为止我的进展:

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");
    }
}
4

7 回答 7

65

这是使用正则表达式的一种方法:

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

\p{Punct}则表达式是表示单个标点字符的 POSIX 模式。

于 2012-12-18T02:41:38.300 回答
28
于 2018-03-15T00:32:26.570 回答
22

你想检查更多的标点符号.吗?

如果是这样,您可以这样做。

String punctuations = ".,:;";//add all the punctuation marks you want.
...
if(punctuations.contains(letter[a]))
于 2012-12-18T02:40:04.813 回答
2

试试这个方法:Character.isLetter()。如果字符是字母(az、大写或小写),则返回 true,如果字符是数字或符号,则返回 false。

例如 boolean answer = Character.isLetter('!');

答案将等于假。

于 2012-12-18T02:39:51.367 回答
1

I have tried regex: "[\\p{Punct}]" or "[\\p{IsPunctuation}]" or withouth [], it doesn't work as expected.

My string is: How are you?, or even "How are you?", he asked.

Then call: my_string.matches(regex); but it seems like it only recognises if the string is only one punctuation (e.g "?", ".",...).

Only this regex works for me: "(.*)[\\p{P}](.*)", it will include all preceding and proceeding characters of the punctuation because the matches() requires to match all the sentence.

于 2021-06-10T07:45:32.833 回答
-2

import String ... if(string.punctuation.contains(letter[a]))

于 2019-01-31T22:32:08.917 回答
-3

function has_punctuation(str) {

  var p_found = false;
  var punctuations = '`~!@#$%^&*()_+{}|:"<>?-=[]\;\'.\/,';
  $.each(punctuations.split(''), function(i, p) {
    if (str.indexOf(p) != -1) p_found = true;
  });

  return p_found;

}

于 2015-06-17T20:42:49.133 回答