Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1ijPQz-0001fz-2C for pgsql-general@arkaria.postgresql.org; Mon, 23 Dec 2019 15:15:49 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1ijPQx-0001Re-HP for pgsql-general@arkaria.postgresql.org; Mon, 23 Dec 2019 15:15:47 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1ijPQx-0001RW-7J for pgsql-general@lists.postgresql.org; Mon, 23 Dec 2019 15:15:47 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1ijPQv-0000W5-1d for pgsql-general@postgresql.org; Mon, 23 Dec 2019 15:15:46 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.4/8.14.4) with ESMTP id xBNFFehr028144; Mon, 23 Dec 2019 10:15:40 -0500 From: Tom Lane To: "Daniel Verite" cc: pgsql-general@postgresql.org Subject: Re: Mixing greediness in regexp_matches In-reply-to: <306b726b-f185-4668-bffe-ac8e7f78878e@manitou-mail.org> References: <306b726b-f185-4668-bffe-ac8e7f78878e@manitou-mail.org> Comments: In-reply-to "Daniel Verite" message dated "Mon, 23 Dec 2019 15:56:47 +0100" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <28142.1577114140.1@sss.pgh.pa.us> Date: Mon, 23 Dec 2019 10:15:40 -0500 Message-ID: <28143.1577114140@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk "Daniel Verite" writes: > The basic idea is to iterate on the rows produced by > regexp_matches(string, '(.*?)(foo|bar|foobar)', 'g') > to break down the string into pairs of (non-matching segment, > matching segment) so that a final result can be assembled > from that (setting aside the last non-matching segment, that > can be retrieved in a final step). > The difficulty is that the longest strings in the alternation > should be prioritized, but the starting (.*?) makes the RE > non-greedy so "foo" is choosen over "foobar". I'd try forcing the match to be the whole string, ie ^(.*?)(foo|bar|foobar)(.*)$ which would also save some work for restarting the iteration, since you'd have already captured the all-the-rest substring. With the endpoints forced, it doesn't really matter whether the engine deems the RE-as-a-whole to be greedy or not. I think this would work without needing any explicit greediness marking for the second and third parts, but I might be wrong about that detail. regards, tom lane