正则表达式问题 pattern/matcher

Issue with regex pattern/matcher

String s2 = "K000";
Pattern p2 = Pattern.compile("/^.*([A-Z])/");
Matcher m2 = p2.matcher(s2);

if (m2.find()) {    
    int pos2 = m2.end();
    a2 = s2.substring(0,pos2);
    n2 = s2.substring(pos2);
}

我希望 a2 被赋予值 "K" 并且 n2 被赋予值“000”,但是 m2.find() 永远不会计算为真,所以永远不会处理条件语句。我在在线正则表达式测试器上仔细检查了我的正则表达式模式,对于这个字符串和这个模式,它 returns K 作为匹配项。知道我在这里做错了什么吗?

最终,我需要做的是能够从开头 s2 一直分配到找到的最后一个 capitol alpha 到 a2 以及在最后一个 capitol alpha 之后出现的任何小写字母、数字、特殊字符到 n2 .

如有任何帮助,我们将不胜感激。

只需从正则表达式中删除 / 即可。

因此您的最终正则表达式将是 ^.*([A-Z]) 并且 Pattern 对象将按如下方式创建:

Pattern p2 = Pattern.compile("^.*([A-Z])");

这会给你想要的结果。

/ 是 Java 脚本正则表达式分隔符,您不要在 Java 中使用它们。您可能使用了 Java 脚本正则表达式测试器。

See this example:

public static void main(String[] args) {
    String s2 = "K000";
    String a2 = "";
    String n2 = "";

    Pattern p2 = Pattern.compile("^.*([A-Z])");
    Matcher m2 = p2.matcher(s2);
    if (m2.find()) {
        int pos2 = m2.end();
        a2 = s2.substring(0, pos2);
        n2 = s2.substring(pos2);
    }

    System.out.println(a2); // K
    System.out.println(n2); // 000
}

请注意,您还可以使用另一种模式,它看起来更直接一些(并让匹配器为您完成工作)。

See this example:

public static void main(String[] args) {
    String s2 = "K000";
    String a2 = "";
    String n2 = "";

    Pattern p2 = Pattern.compile("([A-Z]+)(.+)");
    Matcher m2 = p2.matcher(s2);
    if (m2.matches()) {
        a2 = m2.group(1);
        n2 = m2.group(2);
    }

    System.out.println(a2); // K
    System.out.println(n2); // 000
}

(如果您不想要求至少一个字符,请将 + 替换为 *