如何使用 Java 中的正则表达式提取顺序未知的命名组?

How do I extract named groups with unknown order with a regular expression in Java?

假设我想从可能包含其中一个或两个的字符串中提取 foo\d{2}bar\d{2} 作为命名组(例如,foobar)以任何顺序,例如:

hello foo33 world bar12
bar66 something foo14
this one only has bar45
this one has neither

有没有办法在 Java 中使用单个正则表达式来实现?

最好能将解决方案推广到 3 个以上的命名组。

您可以使用 (foo|bar)\d{2}find 方法来获取所有需要的值

(foo|bar)\d{2} 要么匹配 foo

  • |bar : 或 bar

  • \d{2} : 正好匹配 2 个数字

代码

    String s="hello foo33 world bar12\n"+
            "bar66 something foo14\n"+
            "this one only has bar45\n"+
            "this one has neither";
    Pattern pattern = Pattern.compile("(foo|bar)\d{2}");
    Matcher matcher = pattern.matcher(s);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }

输出:

foo33
bar12
bar66
foo14
bar45

这可以使用正则表达式或运算符来完成:|

在这种情况下,您要查找 foo bar。因此,您需要做的就是将它们与 或运算符 .

分组
(foo|bar)\d{2}

Here's an example on regexer!