pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Ian Barwick <barwick@gmail.com>
To: Leif B. Kristensen <leif@solumslekt.org>
Cc: pgsql-sql@postgresql.org
Subject: Re: Plpgsql: Assign regular expression match to variable
Date: Tue, 1 Sep 2009 21:36:18 +0900
Message-ID: <1d581afe0909010536g6fdb57a0u87c8d748fb9067b6@mail.gmail.com> (raw)
In-Reply-To: <200909011401.00231.leif@solumslekt.org>
References: <200909011401.00231.leif@solumslekt.org>

2009/9/1, Leif B. Kristensen <leif@solumslekt.org>:
> In Plpgsql, I've got this problem of how to assign an integer extracted
> from a regex to a variable. My approach so far feels kludgy:
>
> -- extract ^#(\d+) from txt
> IF txt SIMILAR TO E'#\\d+%' THEN
>     my_int := SUBSTR(SUBSTRING(txt, E'#\\d+'), 2,
>         LENGTH(SUBSTRING(txt, E'#\\d+')) -1)::INTEGER;
>     -- strip ^#\d+ from text
>     my_txt := REGEXP_REPLACE(txt, E'^#\\d+ ', '');
> END IF;
>
> What I'd like to do is something like this:
>
> my_int := MATCH(txt, '^#(\d+)')::INTEGER;
>
> which would assign the integer atom (\d+) to my_int.

This seems to do what you want:

  my_int := (REGEXP_MATCHES(txt, E'^#(\\d+)'))[1];


Ian Barwick



view thread (3+ messages)  latest in thread

Message-ID: <1d581afe0909010536g6fdb57a0u87c8d748fb9067b6@mail.gmail.com>
Permalink:  ../1d581afe0909010536g6fdb57a0u87c8d748fb9067b6@mail.gmail.com/
Also on:    postgresql.org/message-id/1d581afe0909010536g6fdb57a0u87c8d748fb9067b6@mail.gmail.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: barwick@gmail.com, leif@solumslekt.org
  Subject: Re: Plpgsql: Assign regular expression match to variable
  In-Reply-To: <1d581afe0909010536g6fdb57a0u87c8d748fb9067b6@mail.gmail.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox