C#Regex用于屏蔽电子邮件

时间:2015-02-27 11:30:55

标签: c# regex email

是否有一种使用C#中的正则表达式屏蔽电子邮件地址的简单方法?

我的电子邮件

myawesomeuser@there.com

我的目标

**awesome****@there.com (when 'awesome' was part of the pattern)

所以它更像是一个倒置的替代品,其中实际上不匹配的evertyhing将被替换为*

注意:永远不应该替换域名!

从性能方面来看,按@进行拆分是否更有意义,只检查第一部分然后将其重新组合在一起?

注意:我不想检查电子邮件是否有效。它只是一个简单的倒置替换,只是为了我当前的需要,字符串是一个电子邮件,但肯定它也可以是任何其他字符串。

解决方案

阅读完评论后,我最终得到了一个完全符合我需要的字符串扩展方法。

public static string MaskEmail(this string eMail, string pattern)
{
    var ix1 = eMail.IndexOf(pattern, StringComparison.Ordinal);
    var ix2 = eMail.IndexOf('@');

    // Corner case no-@
    if (ix2 == -1)
    {
        ix2 = eMail.Length;
    }

    string result;

    if (ix1 != -1 && ix1 < ix2)
    {
        result = new string('*', ix1) + pattern + new string('*', ix2 - ix1 - pattern.Length) + eMail.Substring(ix2);
    }
    else
    {
        // corner case no str found, all the pre-@ is replaced
        result = new string('*', ix2) + eMail.Substring(ix2);
    }

    return result;
}

然后可以被称为

string eMail = myawesomeuser@there.com;

string maskedMail = eMail.MaskEmail("awesome"); // **awesome****@there.com

3 个答案:

答案 0 :(得分:3)

string email = "myawesomeuser@there.com";
string str = "awesome";

string rx = "^((?!" + Regex.Escape(str) + "|@).)*|(?<!@.*)(?<=" + Regex.Escape(str) + ")((?!@).)*";

string email2 = Regex.Replace(email, rx, x => {
    return new string('*', x.Length);
});

这里有两个子正则表达式:

^((?!" + Regex.Escape(str) + "|@).)*

(?<!@.*)(?<=" + Regex.Escape(str) + ")((?!@).)*

他们在|(或)

第一个意思是:从字符串的开头,任何字符,但在找到str(转义)或@

时停止

第二个意思是:在此匹配开始之前一定不能有@,并且从str(转义)开始,替换在@ <处停止的任何字符/ p>

可能更快/更容易阅读:

string email = "myawesomeuser@there.com";
string str = "awesome";

int ix1 = email.IndexOf(str);
int ix2 = email.IndexOf('@');

// Corner case no-@
if (ix2 == -1) {
    ix2 = email.Length;
}

string email3;

if (ix1 != -1 && ix1 < ix2) {
    email3 = new string('*', ix1) + str + new string('*', ix2 - ix1 - str.Length) + email.Substring(ix2);
} else {
    // corner case no str found, all the pre-@ is replaced
    email3 = new string('*', ix2) + email.Substring(ix2);
} 

第二个版本更好,因为它可以处理如下角落情况:未找到字符串且电子邮件中没有域。

答案 1 :(得分:0)

(awesome)|.(?=.*@)

试试这个。*$1。但是在开始时会有一个额外的*。从开始的掩码电子邮件中删除*。参见演示。

https://regex101.com/r/wU7sQ0/29

答案 2 :(得分:0)

非RE;

string name = "awesome";
int pat     = email.IndexOf('@');
int pname   = email.IndexOf(name);

if (pname < pat)
    email = new String('*', pat - name.Length).Insert(pname, name) + email.Substring(pat);