Java matcher无法找到最后一个组

Java matcher无法找到最后一个组,java,regex,Java,Regex,过了很长一段时间,我在试regex。我不确定问题是在于正则表达式还是逻辑 String test = "project/components/content;contentLabel|contentDec"; String regex = "(([A-Za-z0-9-/]*);([A-Za-z0-9]*))"; Map<Integer, String> matchingGroups = new HashMap<>(); Pattern pattern = Patter

过了很长一段时间,我在试regex。我不确定问题是在于正则表达式还是逻辑

String test = "project/components/content;contentLabel|contentDec";
String regex = "(([A-Za-z0-9-/]*);([A-Za-z0-9]*))";

Map<Integer, String> matchingGroups = new HashMap<>();

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(test);
//System.out.println("Input: " + test + "\n");
//System.out.println("Regex: " + regex + "\n");
//System.out.println("Matcher Count: " + matcher.groupCount() + "\n");
if (matcher != null && matcher.find()) {
    for (int i = 0; i < matcher.groupCount(); i++) {
         System.out.println(i + " ->  " + matcher.group(i) + "\n");
    }
} 
但是在运行代码时,组提取是关闭的

任何帮助都将不胜感激


谢谢

您有几个问题:

  • 第二个字符类中缺少
    |
  • 在整个正则表达式中有一个不必要的捕获组

  • 当输出组时,您需要使用
    执行此操作,我仍然无法获取最后一个组信息。这是我现在看到的输出------->>0->project/components/content;contentLabel | contentDec 1->项目/组件/content@Sal无需逃避
    /
    完美!这起作用了。很好的解释,尤其是第三点。非常感谢。
    0 ->  project/components/content;contentLabel|contentDec
    1 ->  project/components/content
    2 ->  contentLabel|contentDec
    
    String test = "project/components/content;contentLabel|contentDec";
    String regex = "([A-Za-z0-9-/]*);([A-Za-z0-9|]*)";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(test);
    if (matcher != null && matcher.find()) {
        for (int i = 0; i <= matcher.groupCount(); i++) {
             System.out.println(i + " ->  " + matcher.group(i) + "\n");
        }
    }