This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
The following question is from "A Programmer's Guide to JavaSCJP Certification: A Comprehensive Primer. Third Edition" By Khalid A. Mughal and Rolf W. Rasmussen. It is question 12.14
The answer given is the following (which I also confirmed by running it locally).
However, I don't understand WHY it works. In the regex expression:
doesn't the .? mean match any character 0 or 1 times. So given the input "JAVA JaVa java jaVA" why doesn't it do the following:
[Jj] match the first J
.? match the A (any character)
[Aa] - fail match because the next character is the 'V'
The ".?" could match the A - but then the overall match would fail, as you correctly point out. But it can also match nothing (the "0 times" part) - in which case the rest of expression will also match, for an overall success. A partial match failure causes the regexp engine to backtrack and try other possibilities.
Joined: Nov 29, 2009
Lester Burnham wrote:A partial match failure causes the regexp engine to backtrack and try other possibilities.
Hmm..okay, that was the part I was missing. Thank you!