匹配字符串中的所有字母

时间:2016-06-05 15:04:37

标签: java matcher

我试图找出如果我的字符串包含从a到z&的所有字母。 A到Z.我在下面尝试过:但如果它有aA,它将返回true。我正在寻找所有52个字母,即如果字符串有全部52个字母,那么只有使用Pattern和matcher才能返回true,否则为false。

Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
s=s.replaceAll("\\s+", "");
System.out.println(s);
// String input = "[a-zA-Z]+";
String input = "\\w+";
System.out.println(input);
Pattern pr = Pattern.compile(input);
Matcher m =pr.matcher(s);
if(m.matches()){
    System.out.println("pangram");
} else {
    System.out.println("non-pangram");
}

我们可以通过其他方式解决这个问题,但我试图通过仅使用模式和匹配器来解决它。

2 个答案:

答案 0 :(得分:1)

如果要查看给定输入字符串中是否存在所有52个大写和小写字母,则无法使用正则表达式。它根本无法做到这一点。

如果必须的字符列表是动态的,您可以使用此方法:

private static boolean containsAllOf(String input, String alphabet) {
    boolean[] found = new boolean[alphabet.length()];
    int foundCount = 0;
    for (int i = 0; i < input.length(); i++) {
        char ch = input.charAt(i);
        int idx = alphabet.indexOf(ch);
        if (idx >= 0 && ! found[idx]) {
            found[idx] = true;
            if (++foundCount == found.length)
                return true;
        }
    }
    return false;
}

E.g。像这样使用它:

containsAllOf("abc", "abcdef")                  // returns false
containsAllOf("dfu hadkf kojuhoeuaf", "abcdef") // returns false
containsAllOf("bad fed", "abcdef")              // returns false
containsAllOf("bad fec", "abcdef")              // returns true

如果您特别想要检查英语字母表的全部52个大写和小写字母,可以提高效果。

private static boolean containsAllOfAlphabet(String input) {
    boolean[] found = new boolean[52];
    int foundCount = 0;
    for (int i = 0; i < input.length(); i++) {
        char ch = input.charAt(i);
        int idx = (ch >= 'a' && ch <= 'z' ? ch - 'a' :
                   ch >= 'A' && ch <= 'Z' ? ch - 'A' + 26 : -1);
        if (idx >= 0 && ! found[idx]) {
            found[idx] = true;
            if (++foundCount == found.length)
                return true;
        }
    }
    return false;
}

更新如果想要使用模式匹配器,这是一种方法。

首先对输入字符串的所有字符进行排序,然后使用模式匹配器消除所有非字母和重复字母。如果结果的长度为52,则所有字母都存在。

当然,pangram通常不会认为大写和小写字母不同,因此调用toLowercase()并检查长度26可能更正确:

String input = "Pack my box with five dozen liquor jugs.";

char[] buf = input.toLowerCase().toCharArray();
Arrays.sort(buf);
boolean pangram = (new String(buf).replaceAll("[^a-zA-Z]|([a-zA-Z])\\1+", "$1").length() == 26);
System.out.println(pangram ? "pangram" : "non-pangram");

答案 1 :(得分:-1)

我已经使用了set并将每个字符(ASC)放入其中,因为Set只包含唯一值,因此我检查所有字符的大小== 26。在添加之前使用if(put&gt; = 97&amp;&amp; put&lt; = 122)。

 Scanner sc = new Scanner(System.in);
    String s= sc.nextLine();
    s = s.toLowerCase();
    HashSet<Integer> h = new HashSet<Integer>();
    for (int i = 0; i < s.length(); i++) {
        if(s.charAt(i)!=' '){
            int put = (int)s.charAt(i);
            h.add(put);
        }
    }
    if(h.size()==26)
        System.out.println("all 52");
    else
        System.out.println("missing");
相关问题