For strings with multiple SSN-like sub-strings, this works for Perl versions 5.14+:

c:\@Work\Perl\monks>perl use 5.014; # needed for s///ubstitution /r modifier use warnings; use strict; use Test::More 'no_plan'; use Test::NoWarnings; # use Data::Dump qw(dd pp); # for debug my $rx_semi_strict_ssn = qr{ (?> (?<! \d) \d{3} (\D?) \d{2} \g-1 \d{4} (?! \d)) }xms; my @TESTS = ( 'masking valid ssns', [ '# SSN=123-12-1234 987.65.4321' => '# SSN=XXX-XX-1234 XXX.XX.4321' ], [ '123456789 123 45 6789' => 'XXXXX6789 XXX XX 6789' ], 'no masking (no valid ssns)', [ '12345678 12345123451 123-456789' => '12345678 12345123451 123-456789' ], [ '12-3-45-6789 12345 6789 123-45.6789' => '12-3-45-6789 12345 6789 123-45.6789' ], ); VECTOR: for my $ar_vector (@TESTS) { if (not ref $ar_vector) { note $ar_vector; next VECTOR; } my ($str, $expected) = @$ar_vector; my $got = $str; $got =~ s{ ($rx_semi_strict_ssn) } { $^N =~ s{ (?! \d{1,4} \z) \d }{X}xmsgr }xmsge; ok $got eq $expected, qq{'$str' -> '$expected'}; } # end for VECTOR done_testing; exit; __END__ # masking valid ssns ok 1 - '\# SSN=123-12-1234 987.65.4321' -> '\# SSN=XXX-XX-1234 XXX.XX. +4321' ok 2 - '123456789 123 45 6789' -> 'XXXXX6789 XXX XX 6789' # no masking (no valid ssns) ok 3 - '12345678 12345123451 123-456789' -> '12345678 12345123451 123- +456789' ok 4 - '12-3-45-6789 12345 6789 123-45.6789' -> '12-3-45-6789 12345 67 +89 123-45.6789' 1..4 ok 5 - no warnings 1..5
(A fairly simple change can accommodate this code to pre-5.14 Perl versions — /r modifier not supported; let me know if it's needed.)


Give a man a fish:  <%-{-{-{-<


In reply to Re: masking SSN to last four by AnomalousMonk
in thread masking SSN to last four by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.