Java Stringparsing with Regexp

I am trying to parse String with Regexp to get parameters from it. As an example:

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

My test code is:

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 prints "part1" Can someone tell me?

thanks

+3
source share
2

regexp

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

println.

if (matcher.find())
    for (int i = 1; i <= matcher.groupCount(); ++i)
        System.out.println(matcher.group(i));
+2

, - ... , . , , , "part1", "part2", .

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

Source: https://habr.com/ru/post/1715806/


All Articles