Greediness or non-greediness is only one rule that Perl applies, and it's not the most important rule. The most important rules are (in that order):
- Find a match.
- Of all the possible matches, find one that starts the left most in the query string.
- If a regex can make choices (alternation, repetition) in multiple places (for instance two alternations, two repetitions, or an alternation and a repetition), choices on the left are more significant than choices on the right. That is, it will try all possibilities of the choice on the right before trying the second alternative of the choice on the left.
- In alternation, choices on the left are tried before choices on the right.
- In repetion, greedy choices are preferred over non-greedy once - except when there is a ? modifier, then non-greedy choices are preferred over greedy ones.