Re: Mixing greediness in regexp_matches

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "Daniel Verite" <daniel(at)manitou-mail(dot)org>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Mixing greediness in regexp_matches
Date: 2019-12-23 15:15:40
Message-ID: 28143.1577114140@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

"Daniel Verite" <daniel(at)manitou-mail(dot)org> 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

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2019-12-23 15:26:15 Re: Mixing greediness in regexp_matches
Previous Message Daniel Verite 2019-12-23 14:56:47 Mixing greediness in regexp_matches