Java OCA OCP Practice Question 3116

Question

Consider the following program:

import java.util.regex.Pattern;

public class Main {
       public static void main(String []args) {
              String pattern = "a*b+c{3}";
              String []strings = { "abc", "abbccc", "aabbcc", "aaabbbccc" };
              for(String str : strings) {
                      System.out.print(Pattern.matches(pattern, str) + " ");
              }//  w w w.  j a v  a 2  s.c  om
       }
}


Which one of the following options correctly shows the output of this program?

a) true true true true
b) true false false false
c) true false true false
d) false true false true
e) false false false true
f) false false false false


d)

Note

Here are the following regular expression matches for the character x:

  • x* means matches with x for zero or more times.
  • x+ means matches with x for one or more times.
  • x{n} means match x exactly n times.

The pattern a*b+c{3} means match a zero or more times, followed by b one or more times, and c exactly three times.

So, here is the match for elements in the strings array:

For  "abc", the match fails, resulting in false.
For  "abbccc", the match succeeds, resulting in true.
For  "aabbcc", the match fails, resulting in false.
For  "aaabbbccc", the match succeeds, resulting in true.



PreviousNext

Related