I need to mask the last 4 digits but not hyphen (-) in a credit card number.
For example if I have a string like “1234-5678-9123-4567-891”, the output should be “xxxx-xxxx-xxxx-xxx7-891”. If I have a string like “1234-5678-9123-4567” then the output should be “xxxx-xxxx-xxxx-4567” and for a string like “123456789123” the output should be “xxxxxxxx9123”.
In any case the last 4 digits should be visible. If in a odd string (just like first example), the last 4 digits including hyphen(if any) should be visible.
Thanks
Tried below but not working in all cases—
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;
});
}