3

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
  • You can use the following site to check your REGEX against test cases: regex101.com Commented May 26, 2017 at 19:52

2 Answers 2

2

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));
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.