Given the code fragment:
String s = “Java 7, Java 6”;
Pattern p = Pattern.compile(“Java.+\\d”);
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group());
}
What is the result?
A.
Java 7
B.
Java 6
C.
Java 7, Java 6
D.
Java 7
java 6
E.
Java
The correct asnwer is D as it finds the 2 patterns and print eachone ona separate line as we have println()
No, answer C is correct as there is a greedy quantifier of any character (.+)
run:
Java 7, Java 6
BUILD SUCCESSFUL (total time: 1 second)
——————
compile it:
—————-
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Frage118 {
public static void main(String[] args) {
String s = “Java 7, Java 6”;
Pattern p = Pattern.compile(“Java.+\\d”);
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group());
}
}
}
C. ” 7, Java ” matches “.+” so the whole string matches “Java.+\\d”.
Thank you!
“Java.+\\d” indicates string starting with “Java” and ending with any digit
C is correct