用于屏蔽电子邮件的 C# 正则表达式

C# Regex for masking E-Mails

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

我的电子邮箱:

myawesomeuser@there.com

我的目标

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

所以它更像是一个倒置替换,其中实际上不匹配的所有内容都将替换为 *

注意:永远不要替换域名!

从性能的角度来看,按 @ 拆分并仅检查第一部分然后再将其放回原处是否更有意义?

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

解决方案

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

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
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开始(转义),替换任何停在[=16=的字符]

可能faster/easier阅读:

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);
} 

第二个版本更好,因为它处理极端情况,例如:未找到字符串和电子邮件中没有域。

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

通过 * 尝试 this.Replace。但是 start.So 处会有一个额外的 * 从来自 start.See演示。

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

不回复;

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);