The +
after another quantifier means "don't allow the regex engine to backtrack into whatever the previous token has matched". (See a tutorial on possessive quantifiers here).
So when you apply .*foo
to "xfooxxxxxxfoo"
, the .*
first matches the entire string. Then, since foo
can't be matched, the regex engine backtracks until that's possible, achieving a match when .*
has matched "xfooxxxxxx"
and foo
has matched "foo"
.
Now the additional +
prevents that backtracking from happening, so the match fails.
When you write (.*)+foo
. the +
takes on an entirely different meaning; now it means "one or more of the preceding token". You've created nested quantifiers, which is not a good idea, by the way. If you apply that regex to a string like "xfoxxxxxxxxxfox"
, you'll run into catastrophic backtracking.