CodingButStillAlive
CodingButStillAlive

Reputation: 763

Retrieving capturing groups from Regex Matcher

How would I parse the two numbers in the following string:

String fName = "Run_1_vs_2_pw_optimal_mapping.txt";

I tried it like this, but it doesn't work:

    Pattern filePatt = Pattern.compile("Run_(\\d+)_vs_(\\d+)_", Pattern.CASE_INSENSITIVE);

    Matcher scanner = this.filePatt.matcher(fName);
    while (scanner.find()) {
            int groupSize = scanner.groupCount();
            if (groupSize == 2) {
                firstRun = Integer.parseInt(scanner.group(0));
                secondRun = Integer.parseInt(scanner.group(1));
            }
            break;
     }

However, this doesn't work, because scanner.group(0) returns Run_1_vs_2. But why?

Upvotes: 0

Views: 1100

Answers (2)

tjltjl
tjltjl

Reputation: 1479

See the documentation.

Capturing groups are indexed from left to right, starting at one. Group zero denotes the entire pattern, so the expression m.group(0) is equivalent to m.group().

Use group(1) and group(2).

Upvotes: 2

Martin Ender
Martin Ender

Reputation: 44279

Because the group number 0 corresponds to the full match. The captures are counted from 1. What you want is captures 1 (first set of parentheses) and 2 (second set of parentheses).

Upvotes: 2

Related Questions