What will the program print when compiled and run?
public class Main { public static void main(String[] args) { matchMaker("X.*z", "XyzXyz Xz"); // (1) matchMaker("X.+z", "XyzXyz Xz"); // (2) matchMaker("X.*?z", "XyzXyz Xz"); // (3) matchMaker("X.+?z", "XyzXyz Xz"); // (4) }/* ww w. ja v a 2 s . com*/ public static void matchMaker(String regStr, String target) { Matcher matcher = Pattern.compile(regStr).matcher(target); System.out.print("|"); while(matcher.find()) { System.out.print(matcher.group() + "|"); } System.out.println(); } }
Select the one correct answer.
(a) |Xyz|Xyz|Xz|//from ww w . j a va 2s .com |XyzXyz|Xz| |Xyz|Xyz|Xz| |Xyz|Xyz| (b) |XyzXyz Xz| |XyzXyz Xz| |Xyz|Xyz|Xz| |Xyz|Xyz| (c) |XyzXyz Xz| |XyzXyz|Xz| |XyzXyz Xz| |XyzXyz|Xz| (d) The program will throw an exception when run.
(b)
The application of a* and a+ is greedy in (1) and (2).
A greedy quantifier reads the whole target string and backtracks to match as much of the input as possible.
The application of a*? and a+? is reluctant in (3) and (4).
A reluctant quantifier only reads enough of the input to match the regular expression.
The substring Xz
is not matched by X.+?z, as it requires non-empty input between X and z.