Re: back references using regex

From: Michael Fuhr <mike(at)fuhr(dot)org>
To: Matthew Peter <survivedsushi(at)yahoo(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: back references using regex
Date: 2005-09-08 13:18:06
Message-ID: 20050908131806.GA68886@winnie.fuhr.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

[Please copy the mailing list on replies so others can participate
in and learn from the discussion.]

On Wed, Sep 07, 2005 at 10:40:22PM -0700, Matthew Peter wrote:
> I did read the docs ;) I always do. The question I
> really wanted answered is how to reference the back
> references in my regular expressions parentheses. Like
> the 2nd position or 4th from a group. Like \2 or $2.
> Can I do this in postgres in the query?

Are you looking for something like this?

SELECT substring('abc.foo.foo.xyz' FROM '(([[:alpha:]]+)\\.\\2)');
substring
-----------
foo.foo
(1 row)

That is, one or more alphabetic characters followed by a dot followed
by the same set of characters (this is a simplistic example: it would
also match 'foo.oog' and return 'oo.oo').

Note that the back reference is \2 because it refers to the inner
set of parentheses (i.e., the subexpression with the second opening
parenthesis); the outer set is used here for capturing. And again,
note the escaped backslashes because we're using ordinary quotes.
With dollar quotes the above query would be:

SELECT substring('abc.foo.foo.xyz' FROM $$(([[:alpha:]]+)\.\2)$$);

--
Michael Fuhr

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Bohdan Linda 2005-09-08 13:39:50 Re: Partial commit within the trasaction
Previous Message pobox@verysmall.org 2005-09-08 13:04:32 Re: change column data type from smallint to integer