Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Replace exclude first and nth character

Tags:

c#

regex

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?

like image 701
G. Siganos Avatar asked Nov 22 '19 08:11

G. Siganos


2 Answers

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********

like image 182
Wiktor Stribiżew Avatar answered Nov 12 '22 23:11

Wiktor Stribiżew


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

like image 23
Fabio Avatar answered Nov 12 '22 22:11

Fabio