我需要屏蔽信用卡(如果数字 >=12 且 <=19) and account number (if digits == 8 or 9). Following should be input/output for various strings--
123456789123 -> xxxxxxxx9123
1234-5678-9123-4567 -> xxxx-xxxx-xxxx-4567
1234-5678-9123-4567-891 --> xxxx-xxxx-xxxx-xxx7-891
123123123123131For8640 --> xxxxxxxxxx3131For8640
123123123123131至123123123123177 --> xxxxxxxxxxx3131至xxxxxxxxxxx3177
12345678 --> xxxx5678
我用我的信用卡(123456789012345)支付2700美元到我的账户(12345678) --> 我用我的信用卡(xxxxxxxxxx2345)支付2700美元到我的账户(xxxx5678)。
请注意,在任何情况下,最后 4 位数字都应该只可见(包括连字符)。
以下代码适用于所有情况,除非信用卡号的位数为奇数。例如 13,15 或 19。这种情况不适用于以下代码 -- >
1234-5678-9123-4567-891 --> xxxx-xxxx-xxxx-xxx7-891
private static string MaskIfAccountNumber(this string text)
{
if (string.IsNullOrEmpty(text))
return text;
return Regex.Replace(text, "[0-9][0-9 ]{6,}[0-9]", match =>
{
string digits = string.Concat(match.Value
.Where(c => char.IsDigit(c)));
return digits.Length == 8 || digits.Length == 9
? new string('x', digits.Length - 4) + digits.Substring(digits.Length - 4)
: match.Value;
});
}
public static string MaskIfContainCreditCardPanorAcctNum(this string value)
{
if (string.IsNullOrEmpty(value))
return value;
var maskedAccountNumber = value.MaskIfAccountNumber();
return MaskCreditCardNo(maskedAccountNumber);
}
public static string MaskCreditCardNo(this string value)
{
if (string.IsNullOrWhiteSpace(value))
return value;
return Regex.Replace(value, "(\\d[\\s|-]?){10,}\\d", match =>
{
string CCnumber = match.Value;
string digits = string.Concat(CCnumber
.Where(c => char.IsDigit(c)));
return (digits.Length >= 12 && digits.Length <= 19) ?
Regex.Replace(CCnumber.Substring(0, CCnumber.Length - 4), @"\d", "x") + CCnumber.Substring(CCnumber.Length - 4) : match.Value;
});
}
您可以使用:
(?<=(?<![\d-])(?=(?:-?\d){12,19}(?![\d-]))[\d-]*)\d(?!(?:-?\d){0,3}(?![\d-]))