Created
November 16, 2020 00:06
-
-
Save ShawInnes/e59508968575dff4b2dc67362bcf3ddb to your computer and use it in GitHub Desktop.
Mask a string, works for various lengths
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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