Java OCA OCP Practice Question 2555

Question

Consider the following program and predict the output:

import java.util.regex.*;

public class Main {
    public static void main(String[] args) {
            String str = "OCPJP 2013 OCPJP7";

            Pattern pattern = Pattern.compile("\\b\\w+\\D\\b");
            Matcher matcher = pattern.matcher(str);
            while(matcher.find()) {
                    System.out.println(matcher.group());
            }//from   ww  w .ja v a2 s.  c  o  m
    }
}
a)    OCPJP//ww w.  j a va2 s. c  om
      2013
      OCPJP7

b)    OCPJP
      2013

c)    OCPJP
      OCPJP7

d)  This program does not result in any output.


b)

Note

The expression "\b" matches the word boundaries.

The first "\b" matches the string start, "\w+" matches to OCPJP, "" matches white space, and "\b" matches the starting of the second word.

Thus, it prints OCPJP in the first line.

Similarly, "\b" matches the starting of the second word, "\w+" matches to 2013, "\D" matches to white space, and "\b" matches to the start of the third word.

Therefore, the program prints 2013 in the second line.

However, for the last word, "\b" matches to the start of the third word, "\w+" matches to the OCPJP7, but "\D" did not match with anything; hence, the third word is not printed.




PreviousNext

Related