I need to mask the credit card (if digits >=12 and <=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 –> xxxxxxxxxxx3131For8640
123123123123131to123123123123177 –> xxxxxxxxxxx3131toxxxxxxxxxxx3177
12345678 –> xxxx5678
I m paying 2700 dollars with my credit card(123456789012345) to my account(12345678) –> I m paying 2700 dollars with my credit card(xxxxxxxxxxx2345) to my account(xxxx5678).
Note that in any case last 4 digits should only be visible(including hyphen).
The below code works in all cases except when the the credit card number has the odd total number of digits. For e.g 13,15 or 19. This case does not work with below code — >
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;
});
}