in reply to regex greediness

The (.*?) in your second attempt is a non-greedy match, which means it will match the smallest possible substring that satisfies the pattern. In this case, it matches an empty string because the optional (?:b=(\w))? can also match the empty string. Use a positive lookahead assertion to ensure that the (.*?) matches up to the optional b=(\w) part, but doesn't include it:
/(a)(?:(.*?)(?:b=(\w)))?/

Replies are listed 'Best First'.
Re^2: regex greediness
by choroba (Cardinal) on May 29, 2024 at 19:25 UTC
    (?:...) is a non-capturing group, positive lookahead uses (?=...) which I can't find in the regex used.

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
        (?:...) is a non-capturing group, positive lookahead uses (?=...) which I can't find in the regex used.
      Sorry for the typo, meant to type this, but it's still wrong:
      /(a)(?=(.*?)(?:b=(\w)))?/
      This seems to work:
      /(a)(.*?)(?=b=(\w)|\z)/