-2

When i use this code, i don't have the expected result :

    pattern = Pattern.compile("create\\stable\\s(\\w*)\\s\\(", Pattern.CASE_INSENSITIVE);
    matcher = pattern.matcher("create table CONTACT (");
    if(matcher.matches()) {
        for(int i =0; i<matcher.groupCount();i++) {
            System.out.println("table : " + matcher.group(i) + matcher.start(i) + " - " + matcher.end(i));
        }
    }
}

I expect to catch CONTACT but the regex catch the whole expression "create table CONTACT (". Has someone an idea of the problem ?

Thanks

2 Answers2

1

The regex engine actually counts the entire regex as a group. The first group in your regex is actually the second group returned by the match, which is at index 1.

If you ignore the first group, then you should find what you're looking for in the second.

The reason that the group isn't printed by your code is that groupCount doesn't count the entire regex as a group, so you're only getting 1 group in your loop.

Group zero denotes the entire pattern by convention. It is not included in this count.

You probably don't need a loop, and you can just extract the desired string directly with group(1).

Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
0

Group number starts from 1, not from 0.

Following expression:

matcher.group(i)

should be replaced with:

matcher.group(i+1)

Or simply print group 1 if you want print only one group:

System.out.println("table: " + matcher.group(1));
falsetru
  • 357,413
  • 63
  • 732
  • 636