I am trying to mask a string
name with * (asterisks) and exclude both the first and nth (5th) characters.
Example:
UserFirstName -> U****F*******
I managed to exclude the first character with (?!^).
:
var regex = new Regex("(?!^).");
var result = regex.Replace(stringUserName, "*");
output:
UserFirstName -> U************
How can I also exclude the character in the 5th position?
You may use
(?!^)(?<!^.{4}).
See the regex demo
Pattern details
(?!^)
- (it is equal to (?<!^)
lookbehind that you may use instead) a negative lookahead that fails the position at the start of string (?<!^.{4})
- a negative lookbehind that fails the match if, immediately to the left of the current position, there are any four characters other than a newline char from the start of the string.
- any single char other than a newline char.C# demo:
string text = "UserFirstName";
int SkipIndex = 5;
string pattern = $@"(?!^)(?<!^.{{{SkipIndex-1}}}).";
Console.WriteLine(Regex.Replace(text, pattern, "*"));
Output: U***F********
Without Regex, extra explanation not required ;)
var text = "UserFirstName";
var skip = new[] { 0, 4 }.ToHashSet();
var masked = text.Select((c, index) => skip.Contains(index) ? c : '*').ToArray();
var output = new String(masked);
Console.WriteLine (output); // U***F********
c# Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With