Re: Emulating flexible regex replace

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: twoflower <standa(dot)kurik(at)gmail(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Emulating flexible regex replace
Date: 2014-10-23 14:15:33
Message-ID: 25041.1414073733@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

twoflower <standa(dot)kurik(at)gmail(dot)com> writes:
> Supposing *source* matches the /source pattern/, the $/n/ expressions inside
> the /target pattern/ correspond to the captured groups inside *source*.

> Example:

> Source: 123 source text
> Target: 123 target text
> Source pattern: ([0-9]+) source text
> Target pattern: $1 target text

> This yields a successful match since $1 in the /target pattern/ is replaced
> by "123" from the first captured group in *source* and the resulting string,
> "123 target text", matches the /target pattern/.

> I would like to execute a query which for a given /source pattern/ and
> /target pattern/ returns all rows from the *SEGMENT* table where *source*
> matches the /source pattern/ and *target* matches the /target pattern/ after
> it has its references replaced with the actual captured groups.

> I believe this is not possible since *regexp_replace* expects a string as
> its /replacement/ argument which is not enough in this case.

Well, you could pull out the source text captures with regexp_matches,
escape them somehow (don't think there's a built-in function for that),
insert them into the target pattern with regexp_replace, and then apply
the target pattern with a simple regexp match operator. Kinda tedious,
but hardly "not possible".

A lot of people feel that this sort of text-mashing requirement is best
handled in plperl, but if you don't want to use that for some reason,
it's surely possible in plpgsql.

regards, tom lane

In response to

Browse pgsql-general by date

  From Date Subject
Next Message David G Johnston 2014-10-23 15:45:00 Re: Emulating flexible regex replace
Previous Message twoflower 2014-10-23 14:03:11 Emulating flexible regex replace