ggui ggui - 23 days ago 6
C# Question

Regex to get first 6 and last 4 characters of a string

I would like to use regex instead of string.replace() to get the first 6 chars of a string and the last 4 chars of the same string and substitute it with another character:

&
for example. The string is always with 16 chars. Im doing some research but i never worked with regex before. Thanks

Answer

If you prefer to use regular expression, you could use the following. The dot . will match any character except a newline sequence, so you can specify {n} to match exactly n times and use beginning/end of string anchors.

String r = Regex.Replace("123456foobar7890", @"^.{6}|.{4}$", 
                m => new string('&', m.ToString().Length));

Console.WriteLine(r); //=> "&&&&&&foobar&&&&"

If you want to invert the logic, replacing the middle portion of your string you can use Positive Lookbehind.

String r = Regex.Replace("123456foobar7890", @"(?<=^.{6}).{6}",
                m => new string('&', m.ToString().Length));

Console.WriteLine(r); //=> "123456&&&&&&7890"