The difference between the exact greedy / reluctant X {n}?

In the documentation for the Java Pattern class, I see that the exact quantifier X{n} has both greedy and reluctant forms:

Greedy quantifiers

  • X {n} X, exactly n times
  • ...

Insufficient quantifiers

  • X {n}? X exactly n times
  • ...

The documentation provides general examples of the difference between greedy and reluctant behavior, but does not provide examples for exact quantifiers.

At first I thought: โ€œWell, maybe the difference is that X itself could have been matched in different ways.โ€ But then X can have its own greedy / reluctant specifiers inside it, and, of course, I tested it, and that is no difference ( greedy vs reluctant ).

Given that in any case, it will exactly match n times, is there a difference between the behavior of the two?

+6
source share
1 answer

Reluctance against the greedy only makes sense when a variable length match is possible; a reluctant quantifier will correspond to the minimum possible and greedy maximum.

To distinguish behavior of a limited value, it must have a range, i.e. the quantity must have different minimum and maximum values. To illustrate:

Given input 1234567 , captured groups:

 (\d{2,3})(\d+) -> (123)(4567) (\d{2,3}?)(\d+) -> (12)(34567) 

When there is only a fixed value, for example \d{2} , is there no difference in behavior, adding ? .

+5
source

All Articles