Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing group inside non capturing group

Tags:

java

regex

I'm currently struggling parsing a String which resembles a version.

My regex so far v(\\d+)_(\\d+)(?:_(\\d+))? which should match a String in the following format: vVersion_InterimVersion_PatchVersion. My aim is, that the last matching group (_PatchVersion) is optional.

My problem is the optional part. A String v1_00 will give me a matcher.groupCount of 3. I would have expected a groupCount of 2. So I guess either my regex is wrong or I'm having trouble understanding 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));
      }
      // ...

    }
}
like image 530
user871611 Avatar asked Oct 22 '25 04:10

user871611


1 Answers

There are as many groups as there are capturing groups in the regex. If you have 3 sets of unescaped parentheses in your pattern, there will be matcher.group(1), matcher.group(2) and matcher.group(3).

If Group 3 does not match, its value is null. Check Group 3 for the null value:

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

See the Java online demo:

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);
}

Results: 1 > 0 > 0.

like image 137
Wiktor Stribiżew Avatar answered Oct 23 '25 19:10

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!