【问题标题】:How to mask credit card number except the last four digits using Regex如何使用正则表达式屏蔽除最后四位数字外的信用卡号码
【发布时间】:2020-09-29 22:10:34
【问题描述】:

我正在尝试解决一个问题,即我输入了此人的姓名、他的信用卡号。它必须识别该卡来自哪家公司,并且还必须掩盖除最后四位之外的号码的数字。例如以下几行

'Preston: 345678901234567'
'601234123456737 is a Discover card'

会变成

'Preston: ....4567'
'....6737 is a Discover card'

到目前为止,我已经完成了如何使用 http://www.regular-expressions.info/creditcard.html 验证卡公司的输入:

American Express: ^3[47][0-9]{13}$ 
Discover: ^6(?:011|5[0-9]{2})[0-9]{12}$
MasterCard: ^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$
Visa: ^4[0-9]{12}(?:[0-9]{3})?$

我对如何屏蔽除最后四位数字之外的其余数字感到困惑,并且没有很多文章和资源可以提供帮助。

【问题讨论】:

标签: regex perl credit-card


【解决方案1】:

以下代码演示了如何在除最后四位之外的所有数字上屏蔽 CC 号码。

  • 从用户(姓名、号码)处获取数据
  • 在循环中针对每张卡的正则表达式检查数字
  • 如果数字匹配正则表达式
  • 屏蔽除最后四位以外的所有数字
  • 打印消息
  • 离开循环
use strict;
use warnings;
use feature 'say';

my %re_cc = (
        'American Express'  => qr/^3[47][0-9]{13}$/,
        'Discover'          => qr/^6(?:011|5[0-9]{2})[0-9]{12}$/,
        'MasterCard'        => qr/^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$/,
        'Visa'              => qr/^4[0-9]{12}(?:[0-9]{3})?$/
);

while( my $record = <DATA> ) {
    chomp $record;
    my( $name, $number ) = split ' ', $record;
    while( my ($cc_name,$cc_regex) = each %re_cc ) {
        if( $number =~ /$cc_regex/ ) {
            $number =~ s/(\d+)(?=\d{4})/'*' x length($1)/e;
            say "$name\t$number\n$number is a $cc_name";
            last;
        }
    }
}

__DATA__
Preston     345678901234567

输出

Preston ***********4567
***********4567 is a American Express

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多