tags:

views:

98

answers:

2

I try to parse a String with a Regexp to get parameters out of it. As an example:

String: "TestStringpart1 with second test part2"
Result should be: String[] {"part1", "part2"}
Regexp: "TestString(.*?) with second test (.*?)"

My Testcode was:

String regexp = "TestString(.*?) with second test (.*?)";
String res = "TestStringpart1 with second test part2";

Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(res);
int i = 0;
while(matcher.find()) {
    i++;
    System.out.println(matcher.group(i));
}

But it only outputs the "part1" Could someone give me hint?

Thanks

+1  A: 

may be some fix regexp

String regexp = "TestString(.*?) with second test (.*)";

and change println code ..

if (matcher.find())
    for (int i = 1; i <= matcher.groupCount(); ++i)
  System.out.println(matcher.group(i));
Thanks that was it.
mknjc
A: 

Well, you only ever ask it to... In your original code, the find keeps shifting the matcher from one match of the entire regular expression to the next, while within the while's body you only ever pull out one group. Actually, if there would have been multiple matches of the regexp in your string, you would have found that for the first occurence, you would have got the "part1", for the second occurence you would have got the "part2", and for any other reference you would have got an error.

while(matcher.find()) {

    System.out.print("Part 1: ");
    System.out.println(matcher.group(1));

    System.out.print("Part 2: ");
    System.out.println(matcher.group(2));

    System.out.print("Entire match: ");
    System.out.println(matcher.group(0));
}
Dirk