繁体   English   中英

非捕获组内的捕获组

[英]Capturing group inside non capturing group

我目前正在努力解析类似于版本的String。

到目前为止我的正则表达式v(\\\\d+)_(\\\\d+)(?:_(\\\\d+))? 它应与以下格式的字符串匹配: v Version _ InterimVersion _ PatchVersion 我的目标是,最后一个匹配组( _ PatchVersion )是可选的。

我的问题是可选部分。 字符串v1_00将使我的matcher.groupCount为3。我期望的groupCount为2。所以我猜我的正则表达式有误,或者我在理解matcher.groupCount遇到问题。

public static void main(final String[] args) {

    final String versionString = "v1_00";

    final String regex = "v(\\d+)_(\\d+)(?:_(\\d+))?";

    final Matcher matcher = Pattern.compile(regex).matcher(apiVersionString);
    if (matcher.matches()) {

      final int version = Integer.parseInt(matcher.group(1));
      final int interimVersion = Integer.parseInt(matcher.group(2));
      int patchVersion = 0;
      if (matcher.groupCount() == 3) {
        patchVersion = Integer.parseInt(matcher.group(3));
      }
      // ...

    }
}

正则表达式中的组数与捕获组数相同。 如果您的模式中有3组未转义的括号,则将有matcher.group(1)matcher.group(2)matcher.group(3)

如果组3不匹配,则其值为null 检查组3的值:

if (matcher.group(3) != null) {
    patchVersion = Integer.parseInt(matcher.group(3));
}

参见Java在线演示

final String versionString = "v1_00";
final String regex = "v(\\d+)_(\\d+)(?:_(\\d+))?";
final Matcher matcher = Pattern.compile(regex).matcher(versionString);
if (matcher.matches()) {
    final int version = Integer.parseInt(matcher.group(1));
    final int interimVersion = Integer.parseInt(matcher.group(2));
    int patchVersion = 0;
    if (matcher.group(3) != null) {
        patchVersion = Integer.parseInt(matcher.group(3));
    }
    System.out.println(version + " > " + interimVersion  + " > " + patchVersion);
}

结果: 1 > 0 > 0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM