# Regular Expressions and greedy quantifier

Jennifer Schwartz
Ranch Hand
Posts: 46

Pattern is a?
0 1 a
1 1
2 3 a
3 3

How I read this output: match at index 0 and ending at 1
match at index 1 and ending at 1 **
match at index 2, ending at 3
match at index 3, ending at 3 **

On lines 2 and 4 of output: I don't know whether to call this a match since it's actually "b". BUT, the way I interpret this is that ? is a greedy quantifier and needs to include all the chars in the String and (according to K&B book) is a zero or one quantifier. Because of this it has to include even the characters that are a 0 quantifier or 0 match to the pattern. Can someone correct or validate this thought.

Also, is ? as a greedy quantifier always a zero or one quantifier OR does it change based on combinations etc.? And is this true in regards to other quantifiers? I've read over the Oracle/java tutorial and still a little confused. Thanks!

Darryl Burke
Bartender
Posts: 5148
11
You might find the explanations here more illuminating:
http://www.regular-expressions.info/repeat.html

is ? as a greedy quantifier always a zero or one quantifier OR does it change based on combinations etc.?

As a quantifier, yes, the ? is always 'zero-or-one' but when it follows a quantifier it signifies a lazy, or reluctant match. You'll find more (much more) in the other pages of the tutorial I've linked.

Jennifer Schwartz
Ranch Hand
Posts: 46
Thanks Darryl! I wanted to just be sure the game wasn't being changed one me.

Yes, I seen the chart listing the combinations..hoping that aspect won't be on the exam.

Hareendra Reddy
Ranch Hand
Posts: 173
Think of greedy approach as finding largest possible string.
Jennifer wrote:
On lines 2 and 4 of output: I don't know whether to call this a match since it's actually "b".

You can see group function returns a zero length strings it is not actually b.Therefore these can occur at any index except at the
starting of a matched string (since it is already consumed).

Anyone can correct me if i was wrong.

Bert Bates
author
Sheriff
Posts: 8900
5
Regex is a HUGE topic. Entire books have been written about regex.

But, the SCJP exam doesn't go too far into the complexities of this tool. So, while regex is a very interesting topic, in terms of studying for the SCJP you don't have to dig deeper than what we cover in K&B.

hth,

Bert

Jennifer Schwartz
Ranch Hand
Posts: 46
Good to hear, Bert! While I do find it very interesting and will revisit the whole topic, my time now is limited...13 days of study time left. Much appreciation for all the help.