permaculture playing cards*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Regex question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Regex question" Watch "Regex question" New topic
Author

Regex question

Maren Fisher
Greenhorn

Joined: Nov 29, 2009
Posts: 7
The following question is from "A Programmer's Guide to Java SCJP 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'

I don't understand why the .? doesn't match the A

Thank you
Lester Burnham
Rancher

Joined: Oct 14, 2008
Posts: 1337
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.
Maren Fisher
Greenhorn

Joined: Nov 29, 2009
Posts: 7
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!
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Regex question