Re: Simple method to format a string?

From: Andy Colson <andy(at)squeakycode(dot)net>
To: Scott Marlowe <scott(dot)marlowe(at)gmail(dot)com>
Cc: emilu(at)encs(dot)concordia(dot)ca, "pgsql-general(at)postgresql(dot)org >> \"pgsql-general(at)postgresql(dot)org\"" <pgsql-general(at)postgresql(dot)org>
Subject: Re: Simple method to format a string?
Date: 2012-06-20 18:02:37
Message-ID: 4FE2103D.6070900@squeakycode.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 6/20/2012 12:59 PM, Scott Marlowe wrote:
> This pretty much calls for a user defined function. Plpgsql should
> work, but if you're more comfy in perl or tcl there's pl/tcl and
> pl/perl you can try as well.
>
> On Wed, Jun 20, 2012 at 8:43 AM, Emi Lu <emilu(at)encs(dot)concordia(dot)ca> wrote:
>> Good morning,
>>
>> Is there a simply method in psql to format a string?
>>
>> For example, adding a space to every three consecutive letters:
>>
>> abcdefgh -> *** *** ***
>>
>> Thanks a lot!
>> Emi
>>
>> --
>> Sent via pgsql-general mailing list (pgsql-general(at)postgresql(dot)org)
>> To make changes to your subscription:
>> http://www.postgresql.org/mailpref/pgsql-general
>
>
>
This is the perl func I use: sorry about the formatting

-- mask char is 0 (zero). anything else gets copied across
create or replace function applyMask(text, text) returns text as $$
my($mask, $src) = @_;

my $srcAt = 0;
my $srcLen = length($src);
my $result = '';

for my $i (0..length($mask)-1)
{
my $mchar = substr($mask, $i, 1);
if ($mchar eq '0')
{
if ($srcAt >= $srcLen)
{
$result .= ' ';
} else {
$result .= substr($src, $srcAt, 1);
$srcAt++;
}
} else {
$result .= $mchar;
}
}
return $result;
$$ language plperl;

For example:

select applyMask('(000) 000-0000', '1235551313');

In response to

Browse pgsql-general by date

  From Date Subject
Next Message John R Pierce 2012-06-20 18:03:03 Re: efficiency of wildcards at both ends
Previous Message Scott Marlowe 2012-06-20 17:59:00 Re: Simple method to format a string?