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

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

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.

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.

The logic and fix are the same. Patch attached.

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.

Ideally we'd commit a fix for the other bug first, but that's more
complex. I think we should proceed with something like the attached
patch first given that the problems it fixes seem a lot more plausible
than the problems it creates. But perhaps there are other effects I
don't understand, so I'd appreciate a comment.

Regards,
Jeff Davis

Attachment Content-Type Size
v1-0001-Fix-regex-captures-of-empty-strings-for-the-non-g.patch text/x-patch 3.4 KB

Browse pgsql-bugs by date

  From Date Subject
Next Message Rahila Syed 2026-12-02 05:50:46 Re: BUG #19833: ALTER TABLE that rebuilds an extended statistics object silently drops its SET STATISTICS target (st
Previous Message Hayato Kuroda (Fujitsu) 2026-12-02 01:40:00 RE: BUG #18754: Logical replication cannot restart if client sent a copyDone