I want a regular expression that masks first and last characters of a string with * if the string length is less than or equal to 4
Example :
abc --> *b*
abcd --> *bc*
What I have tried so far:
(?!^.?).(?!.{0}$)
CodePudding user response:
var str = "a";
var result = str.Length <= 2 ? "*" : (str.Length <= 4 ? "*" str.Substring(1, str.Length-2) "*": str);
Console.WriteLine(result);
CodePudding user response:
^.(?=.{0,3}$)|(?<!.{4}).$
will match the first characters if only up to 3 characters come after it until the string ends,
and it will only match the last character if there are not 4 or more characters before it
I'm not sure if C# of .net core 3.1 supports look-behind expressions. If not then this may not work.