开发者

email address hiding some characters with c#, regex

I would like replace some the chars of the e-mail addresses with * char.

when a customer make request, I would like to hide some the chars of the e-mail addres like below;

ha~~~~@~~~~ail.com

I would like to do that like that. I would like to show开发者_运维百科 first two chars before @ and last 3 chars after @

but is there any other common way of doing this?


Similar to other responses, but also different. Accepts the .co.uk addresses too.

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class Test
{
        public static void Main()
        {
                String regex = @"(.{2}).+@.+(.{2}(?:\..{2,3}){1,2})";
                String replace = "$1*@*$2";
                List<String> tests = new List<String>(new String[]{
                        "joe@example.com",
                        "jim@bob.com",
                        "susie.snowflake@heretoday.co.uk",
                        "j@b.us",
                        "bc@nh.us"
                });
                tests.ForEach(email =>
                {
                        Console.WriteLine(Regex.Replace(email, regex, replace));
                });
        }
}

Results in:

jo*@*le.com
ji*@*ob.com
su*@*co.uk
j@b.us
bc@nh.us

Though I'm not 100% sure what you want to do with names that only have 2 letters on either side (thus the last two results). But that's my bid. Example


Because your rules are quite simple it might be easier to just use substring to get the characters before and after the @ and then replace them.

Something along the lines of

            int index = email.IndexOf('@');                
            string returnValue = email.Replace(email.Substring(index - 3, 3), "***").Replace(email.Substring(index+1,3), "***");

Although you'll need to first validate that the email address contains enough characters before the @ and change accordingly.


You could do this:

resultString = Regex.Replace(subjectString, "([^@]{2})[^@]*@[^.]*([^.]{3}.*)$", "$1~~~@~~~$2");

This will fail, though, if there are less than three characters after the @ (like in tim@me.com), or less than 2 before the @. What would you want to happen in a case like that?


public static string MaskEmailID(string EmailID)
    {
        MailAddress addr = new MailAddress(EmailID);
        string username = addr.User;
        string domain = addr.Host;
        String regex;
        if (domain.Contains(".com"))
        {
            regex = @"(.{1}).+(.{1})+@(.{1}).+(.{1}(?:\..{2,3}){1,2})";
        }
        else
        {
            regex = @"(.{1}).+(.{1})+@(.{1}).+(.{4}(?:\..{2,3}){1,2})";
        }
        string CharStr1 = new String('*', username.Length - 2);
        string CharStr2 = new String('*', (domain.IndexOf('.') - 2));
        String replace = "$1" + CharStr1 + "$2@$3" + CharStr2 + "$4";
        return Regex.Replace(EmailID, regex, replace);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜