Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1pLRDp-0003fR-56 for pgsql-bugs@arkaria.postgresql.org; Fri, 27 Jan 2023 16:05:01 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1pLRDn-0000kJ-V5 for pgsql-bugs@arkaria.postgresql.org; Fri, 27 Jan 2023 16:04:59 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1pLRDn-0000iL-N6 for pgsql-bugs@lists.postgresql.org; Fri, 27 Jan 2023 16:04:59 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1pLRDl-0000iK-Lk for pgsql-bugs@lists.postgresql.org; Fri, 27 Jan 2023 16:04:59 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.15.2/8.15.2) with ESMTP id 30RG4r1g3334494; Fri, 27 Jan 2023 11:04:53 -0500 From: Tom Lane To: depesz@depesz.com cc: kosiodg@yahoo.com, pgsql-bugs@lists.postgresql.org Subject: Re: BUG #17761: Questionable regular expression behavior In-reply-to: References: <17761-5a78c34533f3ab72@postgresql.org> Comments: In-reply-to hubert depesz lubaczewski message dated "Fri, 27 Jan 2023 13:42:34 +0100" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <3334492.1674835493.1@sss.pgh.pa.us> Date: Fri, 27 Jan 2023 11:04:53 -0500 Message-ID: <3334493.1674835493@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk hubert depesz lubaczewski writes: > On Fri, Jan 27, 2023 at 09:27:35AM +0000, PG Bug reporting form wrote: >> Executing: >> select regexp_matches('a 1x1250x2500', >> '(a).*?([1-9]\d*)\s*x\s*([1-9]\d*)(?:\s*x\s*([1-9]\d*))?'); >> returns: {a,1,1,NULL} >> while executing: >> select regexp_matches('a 1x1250x2500', >> '(a|b).*?([1-9]\d*)\s*x\s*([1-9]\d*)(?:\s*x\s*([1-9]\d*))?'); >> returns: {a,1,1250,2500} >> >> Shouldn't both results be equal? > The problem is, afair, that there is some state in pg's regexp engine > that makes greedy/ungreedy decision once per regexp. Yeah. Without having traced through it, I'm fairly sure that in the first case, we have "(a)" which has no greediness, then ".*?" which is non-greedy, and then that determines the overall greediness as non-greedy, so it goes for the shortest overall match not the longest. In the second case, "(a|b)" is greedy because anything involving "|" is greedy, so we immediately decide we'll be greedy overall. The fine manual explains how you can force greediness or non-greediness when the engine's default rules for that don't do what you want. regards, tom lane