apply text mask

From: Andy Colson <andy(at)squeakycode(dot)net>
To: PostgreSQL <pgsql-general(at)postgresql(dot)org>
Subject: apply text mask
Date: 2009-12-10 22:52:21
Message-ID: 4B217BA5.1020904@squeakycode.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

I need to apply arbitrary masking to a string (think displaying a phone
number).

I searched around but didnt find anything and wondered if there was such
a thing.

I had some perl code that already did it, so it was easy to make it into
a stored proc. I'll paste it below.

use it like:
select applyMask('(000) 000-0000', '1235551313');

returns:
(123) 555-1313

So this email is two fold.

1) is there something already built in that does this?
2) if not, here's one in plperl you can use if you like.

-- zero is the replace character, everything else is copied literally
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;

-Andy

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2009-12-10 23:04:38 Re: Seeking expected return type info for SPI function
Previous Message Glen Barber 2009-12-10 22:46:12 Restore time differences between full database dumps and separate schema/data dumps