using System;
using System.Text.RegularExpressions;
public class Program
{
public static string MaskDigitsKeepFormat(string input, int visibleDigits = 4,
char maskChar = '*')
{
if (string.IsNullOrEmpty(input))
return input;
// Count total digits in the string
int totalDigits = Regex.Matches(input, @"\d").Count;
int digitsToMask = Math.Max(0, totalDigits - visibleDigits);
int maskedCount = 0;
// Replace digits left-to-right until digitsToMask threshold is reached
return Regex.Replace(input, @"\d", match =>
{
if (maskedCount < digitsToMask)
{
maskedCount++;
return maskChar.ToString();
}
return match.Value;
});
}
public static void Main()
{
Console.WriteLine(MaskDigitsKeepFormat("1234-5678-9012-3456")); // ****-****-****-3456
Console.WriteLine(MaskDigitsKeepFormat("+1 (800) 555-0199")); // +* (***) ***-0199
}
}
/*
run:
****-****-****-3456
+* (***) ***-0199
*/