How to do masking in C# ASP.NET

Hi Experts,

I want to mask an ID, inorder to hide the ID from the users, Like you know it should display only last 4 digits, all the other letters should be replaced with "X".

How can I achieve this, These are some of the sample ID's:

520885659
65990170
54-152-2360
421482753
133331738
39-0958286
20-0659631

thx
Dil.
dileepavAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kamal KhaleefaInformation Security SpecialistCommented:
for each number take the count of each number
for example 520885659 is 9 characters
then take first 5 chracters and replace them with X

for example
this function
Right(520885659 , 4)
takes the last 4 digit of the number
Praveen VenuTechnical Project ManagerCommented:
try this
string data = "54-152-2360";
            int charsToShow = 4;
            string resultMasked= new string(char.Parse("*"),data.Length-charsToShow) + data.Substring(data.Length-charsToShow);

Open in new window

dileepavAuthor Commented:
Hi Praveen,

It worked, but the users wanted to see the "-" or special characters as it is.

how can we achieve it? please help.

the string "54-152-2360" should be "XX-XXX-2360

thx
Dil.
Praveen VenuTechnical Project ManagerCommented:
try this
 string data = "54-152-2360";
            int charsToShow = 4;
            string maskedPart= System.Text.RegularExpressions.Regex.Replace(data.Substring(0,data.Length-4), "([0-9])", "*", System.Text.RegularExpressions.RegexOptions.Singleline | System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace);
            string resultMasked = maskedPart + data.Substring(data.Length - charsToShow);

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dileepavAuthor Commented:
Thx Experts.
It worked perfectly.

regards
Dil
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.