0

I'm learning about quantifier and facing problem to understand the Reluctant and Possessive. I read a lot answers from the stackoverflow, oracle documentation and even found good image https://i.stack.imgur.com/DyhJk.png that is describing them in visually. But still confused. Here is my code.

Pattern p = Pattern.compile("a*?");
Matcher m = p.matcher("abclaaakditabdaa");
while(m.find()){
    System.out.println(" Word: " + m.group() );
}

Why this code is not giving output?

My Understanding:

As in image I understand that Reluctant first match the complete string if it not matched then it start from the left side and move to right side by one character. So in my example it will not match the entire string then it will start from the left side to match. So in my example it should print

a
aaa
a
aa

Can you describe what is wrong with my understanding?

  • 1
    `/a*?/` can match an empty string and return it as a valid match since it does not have to match even a single `a`, unlike `/a*/`. See more in the linked question. – Wiktor Stribiżew Nov 17 '16 at 08:06
  • change the pattern to `"a+"` givey ou the output you expect – XtremeBaumer Nov 17 '16 at 08:06
  • `"abclaaakditabdaa".split("[^a]+")` – Tim Biegeleisen Nov 17 '16 at 08:07
  • @XtremeBaumer but why not for a*? –  Nov 17 '16 at 08:09
  • `a*` = a, zero or more times where `a+` = a, one or more times. this site helps a lot with regex: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html – XtremeBaumer Nov 17 '16 at 08:10
  • 1
    `*` means zero or more times, so it will always match. You get the result you said you wanted with `a+` default greedy quantifier. No `?` needed. – coladict Nov 17 '16 at 08:10
  • FYI, *Why this code is not giving output?* - It actually does give the output, [it is just printing all the empty strings](https://ideone.com/xIGtKj) it could find. And it is true: when you want to match at least something, at least 1 char, never use `?` or `*`, use `+`, `{2,}`, etc. – Wiktor Stribiżew Nov 17 '16 at 09:24
  • @WiktorStribiżew a* mean zero or more a. and ? mean match shortest first and then continue. ( Reluctant ) so as first `a` comes in the string then it matched and should print `a` same as continues... –  Nov 17 '16 at 09:53
  • @coladict a* mean zero or more a. and ? mean match shortest first and then continue. ( Reluctant ) so as first `a` comes in the string then it matched and should print `a` same as continues... –  Nov 17 '16 at 11:01

0 Answers0