[英]How to mask first 6 and last 4 digits for a credit card number in .net
我是regex的新手,並且我正嘗試使用正則表達式將將成為會話一部分的信用卡號碼轉換為類似492900 ****** 2222的內容
由於它可能來自任何會話,因此可能在其旁邊包含字符串或格式可能不一致,因此,基本上所有以下內容都應格式化為上面的示例:
它必須是一個正則表達式,用於提取捕獲組,然后我將能夠使用MatchEvaluator將所有不是前6位和后4位的數字(不包括非數字)轉換為*
我在這里看到了很多關於PHP和JS堆棧溢出的示例,但是沒有一個可以幫助我解決此問題。
任何指導將不勝感激
UPDATE
我需要擴展現有的使用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
嘗試Regex: (?<=\\d{4}\\d{2})\\d{2}\\d{4}(?=\\d{4})|(?<=\\d{4}( |-)\\d{2})\\d{2}\\1\\d{4}(?=\\1\\d{4})
說明:
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
如果您擔心性能問題,那么可以通過避免環顧四周和輪流選擇的方式,僅通過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}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.