我想要将电子邮件地址中的某些字符替换为*。
当客户发出请求时,我想要隐藏电子邮件地址中的某些字符,如下所示;
ha~~~~@~~~~ail.com
我想要这样做。 我想显示@前的前两个字符和@后的最后三个字符。
但是还有其他常用的方法吗?
和其他回答类似,但也有所不同。还接受 .co.uk 地址。
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));
});
}
}
结果是:
jo*@*le.com
ji*@*ob.com
su*@*co.uk
j@b.us
bc@nh.us
虽然我不完全确定您想要如何处理两侧只有2个字母的名称(因此是最后两个结果)。 但这是我的建议。示例
由于您的规则非常简单,可以使用substring获取@之前和之后的字符,然后进行替换。
大致如下:
int index = email.IndexOf('@');
string returnValue = email.Replace(email.Substring(index - 3, 3), "***").Replace(email.Substring(index+1,3), "***");
resultString = Regex.Replace(subjectString, "([^@]{2})[^@]*@[^.]*([^.]{3}.*)$", "$1~~~@~~~$2");
但是,如果在@
之后少于三个字符(例如tim@me.com)或在@
之前少于2个字符,则此方法将失败。在这种情况下,您希望发生什么?
jim@to.com
,那么这将给出~~~@~~~com
? - Jim Mischel(.{2}).*@.*(.{2}(?:\..{2,3}){1,2})
-- IDEOne链接:http://www.ideone.com/fvIkr - Brad Christiepublic 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);
}