Duy Đặng Duy Đặng - 13 days ago 7
Java Question

Regular expression $ meta-character

I am trying to understand this code block.

If the

$
meta-character ends the match, why is "I lost my wallets" valid?

I understand that the quantifier
:?
allows for one
:
or none in the search, but why is there 2 of the same answers?

Can you figure out all possible matches for this pattern?


"^I lost my:? (wallet|car|cell phone|marbles)$"


The given answer is:


"I lost my wallet"

"I lost my wallets"

"I lost my: wallet"

"I lost my: wallets"

"I lost my car"

"I lost my car"

"I lost my: car"

"I lost my: car"

"I lost my cell phone"

"I lost my cell phone"

"I lost my: cell phone"

"I lost my: cell phone"

"I lost my marbles"

"I lost my marbles"



http://www.ocpsoft.org/opensource/guide-to-regular-expressions-in-java-part-1
Quiz 2.2

Answer

The question posed in the quiz (scroll down a little) is:

Can you figure out all possible matches for this pattern?

"I lost my:? (wallet|car|cell phone|marbles)"

The answer says:

This is a trick question! Because this regular expression is unlimited (has no beginning ^ and no ending $)

After which is shows the piece of regex that you are looking at.

"I lost my wallets" is valid only with the regex shown above. The second one (in your question) does not allow it.