这种模式有什么问题:Pattern.compile("\\p{Upper}{4}")

Ian*_* Wu 2 java regex

我正在写一个由 4 个大写字母组成的Pattern匹配 a String

例如:

  • “AAAA”
  • “A B C D”
  • “ZZZZ”

...都是正确的匹配,而:

  • “1DFG”
  • “!@#$”
  • “1234”

...应该匹配。

在下面找到我的代码。

它不断返回false“AAAA”。

任何人都可以对此有所了解吗?

public static boolean checkSettings(String str) {
    Pattern p = Pattern.compile("\\p{Upper}{4}");
    Matcher m = p.matcher("%str".format(str));
    if (m.matches()) {
        return true;
    } else {
        // System.exit(1)
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

Men*_*ena 5

我认为您的 没有任何问题Pattern,可能是您的输入有问题String

拿这个例子:

Pattern p = Pattern.compile("\\p{Upper}{4}");
Matcher m = p.matcher("%str".format("AAAA"));
System.out.println(m.find());
Run Code Online (Sandbox Code Playgroud)

输出:

true
Run Code Online (Sandbox Code Playgroud)

警告

\\p{Upper}{4}并且\\P{Upper}{4}相同的Pattern,而是一个彼此相反。

第二个实例否定 4 个大写字符(参见大写“P”)。我指出这一点是因为您的问题标题表明错误Pattern

最后说明

如果您只打算为您的 使用 ASCII 字母字符Pattern,您可能想要使用[A-Z](此处大写重要),正如本线程中的其他人所提到的。它完全等同于\\p{Upper}.

与 略有不同\\p{Lu},这将匹配大写字母Unicode 类别