Java OCA OCP Practice Question 2553

Question

Consider the following program and predict the output:

import java.util.regex.*;

public class Main {
    public static void main(String[] args) {
            String str1 = "xxzz";
            String str2 = "xyz";
            String str3 = "yzz";
            Pattern pattern = Pattern.compile("(xx)*y?z{1,}");
            Matcher matcher = pattern.matcher(str1);
            System.out.println(matcher.matches());
            System.out.println(pattern.matcher(str2).matches());
            System.out.println(/*www  .  jav  a2s .  co  m*/
                    Pattern.compile("(xx)*y?z{1,}").
                    matcher(str3).matches());
    }
}
a)      true//from   w  w  w .jav a  2  s  .  com
     false
     true

b)      true
     false
     false

c)      false
     false
     false

d)      false
     false
     true

e)      true
        true
        true


a)

Note

The specified regex expects zero or more instances of "xx", followed by a zero or one instance of "y" and further followed by one or more instances of "z.".

The first string matches the regex (one instance of "xx," zero instances of "y," and more than one instances of "z"), and thus matches() returns true.

The second string does not match with the regex because of one "x" (and not "xx"), thus matches() returns false.

The third string matches with the specified regex (since there are zero instances of "xx," one instance of "y," and more than one instance of "z"), thus matches() prints true.




PreviousNext

Related