in reply to regex greediness

I thought that using '(.*?)' would match up to 'b'

Why would it do that when it can match zero times?

  1. (a) matches 1 character at position 0.
  2. (.*?) attempts to match . 0 times at position 1.
  3. (.*?) matches 0 character at at position 1.
  4. (?:b=(\w))? attempts to match b=(\w) 1 times at position 1.
  5. b=(\w) fails to match at position 1.
  6. (?:b=(\w))? attempts to match b=(\w) 0 times at position 1.
  7. (?:b=(\w))? matches 0 characters at at position 1.
  8. Successful match.

Replies are listed 'Best First'.
Re^2: regex greediness
by Danny (Chaplain) on May 29, 2024 at 22:20 UTC
    Makes sense!

    EDIT:
      Why would it do that when it can match zero times?
    I guess I was thinking that since (?:b=(\w))? prefers to match once it would influence the behavior of .*? in an analogous way to how (?:b=(\w)) would, which, as you explained, isn't the case.