【问题标题】:With "or" in regex express can not get capture group在正则表达式中使用“或”表示无法获取捕获组
【发布时间】:2021-07-17 10:03:42
【问题描述】:

下面的例子,

    @Test
    public void test10() {
        String str = "idcard=123433198901192, phone=12338219201";
        String regex = "(\\d{4})(\\d{7})(\\d{4})";
        //String regex = "(\\d{4})(\\d{10})(\\d{4})|(\\d{4})(\\d{7})(\\d{4})";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            System.out.println("full match:"+matcher.group());
            System.out.println("1 group capture:"+matcher.group(1));
            System.out.println("2 group capture:"+matcher.group(2));
            System.out.println("3 group capture:"+matcher.group(3));
        }
    }

当我使用"(\\d{4})(\\d{7})(\\d{4})" 时,matcher.group(1)/matcher.group(2)/matcher.group(3)/ 都可以返回捕获结果

full match:123433198901192
1 group capture:1234
2 group capture:3319890
3 group capture:1192

但是当我使用正则表达式"(\\d{4})(\\d{10})(\\d{4})|(\\d{4})(\\d{7})(\\d{4})"时,它无法获得捕获组结果

full match:123433198901192
1 group capture:null
2 group capture:null
3 group capture:null

我猜原因是or (|) 符号,但我不知道为什么,谢谢大家。

【问题讨论】:

  • 捕获组有6个,值在第4、5、6组中
  • 使用像 (a)(b)|(c) 这样的正则表达式有 3 个组:第 1 组是 (a),第 2 组是 (b),第 3 组是 (c)。这些数字以或重新开始。想一想:您将如何处理 ((a)(b)|(c))(d) 之类的情况,具体取决于匹配 (d) 将是第 3 组或第 2 组......所以虽然在最简单的情况下重置编号似乎是有意义的,但它实际上会创建在更复杂的问题中有很多问题。
  • @Thefourthbird @GACy20,谢谢
  • 你为什么不用(\d{4})(\d{10}|\d{7})(\d{4})之类的东西?
  • @Thomas 是的,看起来更好

标签: javascript java regex


【解决方案1】:

如果你想4,7,44,10,4 先消耗较大的长度 10:

(\d{4})(\d{10}|\d{7})(\d{4})

Regex101.com sample

【讨论】:

    猜你喜欢
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 2018-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    相关资源
    最近更新 更多