Regex Replace exclude first and nth character

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

Tags:

C#

Regex