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

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Jeff Davis <pgsql(at)j-davis(dot)com>
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 18:03:40
Message-ID: 1920485.1796234620@sss.pgh.pa.us
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

Jeff Davis <pgsql(at)j-davis(dot)com> writes:
> Regex capture bug found by AI:
> https://ai-annex.j-davis.com/report/01a1e70f-f0d5-7774-bd78-ee50975709e8

> 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 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 see by testing that perl does think this should match; but it's a
different engine with a different definition of greediness, so
I do not consider it to be the final authority on what we should do.

> This problem was already fixed for greedy quantifiers back in
> f2c4ffc330 (so the same pattern works without the '?'), but that commit
> missed the non-greedy case.

That's long enough ago that I don't remember whether I thought of
changing creviterdissect along with citerdissect. Maybe it's the
right thing but I'm unconvinced; especially if changing it changes
other cases we'd rather not change.

> One complication is that (as an AI review of this fix also discovered)
> the patch uncovers another consequence of this bug:
> https://ai-annex.j-davis.com/report/01a1d16e-b15f-727e-9ba0-32f4077864ba
> which is that the contrived pattern:
> 'ab' ~ '(?:.(x*?)??(?:\1|.()))+\2'
> evaluates to true (correct according to perl) on master but false with
> the attached patch.

This is another example where correctness is a pretty squishy
thing to define. It appears to me that that regex is fully
within its rights to not set \2; the only reason it does so is
that it failed to set \1, so that looks like a catch-22.

On the whole these look like extremely low-priority issues.
And I think there's a good chance of making more people unhappy
than happy (because their regex no longer works like it did).

regards, tom lane

In response to

Responses

Browse pgsql-bugs by date

  From Date Subject
Next Message Kirill Reshke 2026-12-02 18:21:38 Re: BUG #19965: btree_gist index on timetz returns too few rows for <, > and <>
Previous Message Sami Imseih 2026-12-02 17:58:58 Re: Anti-wraparound autovacuum stops for good after no slot available for new autovacuum worker process