Re: regex replace credit card numbers with *



cldmismgr <admin@xxxxxxxxxx> wrote:
> I have this little piece of code to replace all but the last 4 numbers
> in a credit card number with *'s. Is there a better way to do this? I
> tried using just a regex but everything I tried failed. For example
> s/^[0-9]{9}/*/ replaced this first 9 digits with one *. The idea is to
> replace each digit with an asterick and leave the last four digits
> alone.
> $st = "*";
> $addr = '123456789012345';
> $size = length($addr) - 4;
> for ($i=0;$i < $size; $i++) {
> $star .= $st;
> }
> print "$addr\n";
> $addr =~ s/^[0-9]{$size}/$star/;
> print "$addr\n$star\n";

One solution would be as follows - note also allows for non-digits
to be interspersed (and ignored).

#!/usr/bin/perl

use strict;
use warnings;

my $st = "*";
my $addr = '1245-4536-8904-2345';
print $addr, "\n";

$addr =~ s/\d/$st/ for (1 .. ($addr =~ tr/0-9//) - 4);

print $addr, "\n";

__END__

Output:

1245-4536-8904-2345
****-****-****-2345

Axel

.



Relevant Pages

  • regex replace credit card numbers with *
    ... in a credit card number with *'s. ... replace each digit with an asterick and leave the last four digits ... Craig ... Prev by Date: ...
    (comp.lang.perl.misc)
  • Re: beginners Digest 13 Mar 2006 05:54:58 -0000 Issue 2791
    ... passed by the Parliament on 15th December 2005 and received Royal Assent ... Here is how I would go about writing the regex needed to pull the information ... Part 7 seems to be a four digit year. ... Next we need to identify the parts we want to capture. ...
    (perl.beginners)
  • Re: How do I do a MOD-10 Credit Card check in Excel?
    ... but it looks like a credit card check multiplies ... variable since entering a 16 digit number would have to be done as a string. ... My credit card showed "Valid" as a check. ... Dim Tot As Long ...
    (microsoft.public.excel.worksheet.functions)
  • Re: Regex in java
    ... string data that is actually a BCD number. ... Seems to me regex can skip over white space. ... So I think it needs either one digit before the. ...
    (comp.lang.java.programmer)
  • Re: Regular Expressions
    ... The following regex ... It is a sequence of capital letters, digits, and certain punctuation, ... If it begins with a digit, then there must be a letter. ... >> Ludovic SOEUR. ...
    (microsoft.public.dotnet.languages.csharp)