如何屏蔽.net中信用卡号的前6位和后4位

时间:2019-02-21 18:19:20

标签: c# asp.net .net regex security

我是regex的新手,我正尝试使用正则表达式将将成为会话一部分的信用卡号转换为类似492900 ****** 2222的内容

由于它可能来自任何对话,因此它可能在其旁边包含字符串或格式可能不一致,因此基本上所有以下内容都应格式化为上面的示例:

  • 你好,我的电话是492900001111222
  • 电话号码是4929000011112222好吗?
  • 4929 0000 1111 2222
  • 4929-0000-1111-2222

它必须是一个正则表达式,用于提取捕获组,然后我将能够使用MatchEvaluator将不是前6位和后4位的所有数字(不包括非数字)转换为*

我在这里看到了很多关于PHP和JS堆栈溢出的示例,但没有一个可以帮助我解决此问题。

任何指导将不胜感激

更新

我需要扩展一个现有的实现,该实现使用MatchEvaluator来掩盖不是前6个或后4个字符的每个字符,理想情况下,我不想更改MatchEvaluator,而只是基于正则表达式使掩盖变得灵活,请参见例如https://dotnetfiddle.net/J2LCo0

更新2

@ Matt.G和@CAustin的答案确实可以解决我的要求,但我遇到了另一个障碍,我无法做到如此严格。最终捕获的组只需要考虑数字,并因此保持输入文本的格式。 例如:

如果我的卡号中的某些类型为99 9988 8877776666,则评估结果应为99 9988 ****** 666666

或 我的卡号是9999-8888-7777-6666,它应该输出9999-88 **-****-6666。

这可能吗?

已将列表更改为包括我的单元测试https://dotnetfiddle.net/tU6mxQ

中的项目

2 个答案:

答案 0 :(得分:1)

尝试使用正则表达式:(?<=\d{4}\d{2})\d{2}\d{4}(?=\d{4})|(?<=\d{4}( |-)\d{2})\d{2}\1\d{4}(?=\1\d{4})

Regex Demo

C# Demo

说明:

2 alternative regexes
(?<=\d{4}\d{2})\d{2}\d{4}(?=\d{4}) - to handle cardnumbers without any separators (- or <space>)
(?<=\d{4}( |-)\d{2})\d{2}\1\d{4}(?=\1\d{4}) - to handle cardnumbers with separator (- or <space>)

1st Alternative (?<=\d{4}\d{2})\d{2}\d{4}(?=\d{4})
    Positive Lookbehind (?<=\d{4}\d{2}) - matches text that has 6 digits immediately behind it
    \d{2} matches a digit (equal to [0-9])
        {2} Quantifier — Matches exactly 2 times
    \d{4} matches a digit (equal to [0-9])
        {4} Quantifier — Matches exactly 4 times
    Positive Lookahead (?=\d{4}) - matches text that is followed immediately by 4 digits
        Assert that the Regex below matches
            \d{4} matches a digit (equal to [0-9])
            {4} Quantifier — Matches exactly 4 times

2nd Alternative (?<=\d{4}( |-)\d{2})\d{2}\1\d{4}(?=\1\d{4})

    Positive Lookbehind (?<=\d{4}( |-)\d{2}) - matches text that has (4 digits followed by a separator followed by 2 digits) immediately behind it
    1st Capturing Group ( |-) - get the separator as a capturing group, this is to check the next occurence of the separator using \1
    \1 matches the same text as most recently matched by the 1st capturing group (separator, in this case)
    Positive Lookahead (?=\1\d{4}) - matches text that is followed by separator and 4 digits

答案 1 :(得分:1)

如果您需要关注性能,则可以通过避免环视和轮换选择,该模式仅经过94个步骤,而不是其他答案的473个步骤:

\d{4}[ -]?\d{2}\K\d{2}[ -]?\d{4}

演示:https://regex101.com/r/0XMluq/4

编辑:在C#的正则表达式中,可以使用以下模式代替,因为C#允许在后面进行变长查找。

(?<=\d{4}[ -]?\d{2})\d{2}[ -]?\d{4}

Demo