Re: Regex fails to capture group consisting of empty string in non-greedy case

From: Jeff Davis <pgsql(at)j-davis(dot)com>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: pgsql-bugs(at)postgresql(dot)org
Subject: Re: Regex fails to capture group consisting of empty string in non-greedy case
Date: 2026-12-02 19:59:19
Message-ID: 85bd1affd2938143163e204f313debe10bcba587.camel@j-davis.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

On Wed, 2026-12-02 at 13:03 -0500, Tom Lane wrote:
> > The pattern '^(a*?)*\1$' should match the empty string, but \1
> > doesn't
> > get set, so the match fails.
>
> Well, meh.  Just because your LLM thinks this is a bug doesn't make
> it
> one.

The argument that convinced me was (adjusted from LLM's example to my
own):

SELECT '' ~ '^(a*?)*\1$'; -- false, should be true

The greedy form '^(a*)*\1$' matches. Greediness is supposed to
decide which match is preferred, not whether there is one, so the two
forms must agree on true/false.

>   The thing that is bothering me about this proposal is that a
> non-greedy pattern is supposed to prefer shortest match, and in
> particular it ought to prefer zero repetitions to one repetition,
> back-refs or no.

I found the LLM's example with '??' confusing for that reason, which is
why I used '^(a*?)*\1$' in the tests for the patch. In my example,
there's only one non-greedy operator, and it's inside the group, and it
still doesn't capture.

Regardless of backrefs, the current code does (see my tests):

=> select regexp_match('', '(a*)*');
regexp_match
--------------
{""}
(1 row)

=> select regexp_match('', '(a*?)*');
regexp_match
--------------
{NULL}
(1 row)

That doesn't seem right.

My tests passed in 9.1 (by using regexp_matches(), because
regexp_match() didn't exist), but all four started failing after commit
173e29aa5. f2c4ffc330 fixed the greedy patterns to be 9.1 behavior, but
not the non-greedy ones.

Regards,
Jeff Davis

In response to

Responses

Browse pgsql-bugs by date

  From Date Subject
Next Message Colin McDonnell 2026-12-02 21:14:58 Re: Anti-wraparound autovacuum stops for good after no slot available for new autovacuum worker process
Previous Message Aman Ganapathy 2026-12-02 19:00:45 Re: BUG #19964: ltree GiST index returns too few rows for lquery with a {0,n} quantifier