【问题标题】:Issue with regex pattern/matcher正则表达式模式/匹配器的问题
【发布时间】:2016-12-13 21:02:58
【问题描述】:
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() 永远不会计算为 true,因此永远不会处理条件语句。我在在线正则表达式测试器上仔细检查了我的正则表达式模式,对于这个字符串和这个模式,它返回 K 作为匹配项。知道我在这里做错了什么吗?

最终,我需要做的是能够从开始 s2 一直分配到最后一个发现到 a2 的国会大厦 alpha 以及在最后一个国会大厦 alpha 到 n2 之后出现的任何小写、数字、特殊字符。

任何帮助将不胜感激。

【问题讨论】:

  • 摆脱/
  • 省略您正在使用的 javascript 正则表达式分隔符,即 Pattern.compile("^.*([A-Z])");
  • Java,javascript,不是一样的吗? ;-P 非常感谢您找出我做错了什么。似乎已经有好几个小时了。

标签: java regex matcher


【解决方案1】:

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

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
}

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

【讨论】:

    【解决方案2】:

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

    所以你的最终正则表达式将是^.*([A-Z])Pattern 对象将按如下方式创建:

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

    这会给你想要的结果。

    【讨论】:

    • 确实如此!
    • @Chad 如果您遇到正则表达式问题,您可以尝试regexr.com。它非常有用。
    猜你喜欢
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 2016-04-20
    • 2011-07-17
    相关资源
    最近更新 更多