Skip to content

Instantly share code, notes, and snippets.

@ShawInnes
Created November 16, 2020 00:06
Show Gist options
  • Save ShawInnes/e59508968575dff4b2dc67362bcf3ddb to your computer and use it in GitHub Desktop.
Save ShawInnes/e59508968575dff4b2dc67362bcf3ddb to your computer and use it in GitHub Desktop.
Mask a string, works for various lengths
public static string MaskString(string inputString)
{
string pattern = "^(.{2}?)(.+)(.{2}?)$";
char maskChar = '*';
if (string.IsNullOrEmpty(inputString))
{
return inputString;
}
if (inputString.Length <= 4)
{
return new string(maskChar, inputString.Length);
}
pattern = "^(.{2}?)(.+)(.{2}?)$";
return Regex.Replace(inputString, pattern, (match) => Regex.Replace(String.Format("{0}{1}{2}",
match.Groups[1].Value,
new string(maskChar, match.Groups[2].Value.Length), // X times the 'X' char
match.Groups[3].Value), ".{2}", "$0"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment