我正在创建一个函数来屏蔽电子邮件地址(除了@
符号前的前两个字母和最后两个字母(,但前两个字符仍然被屏蔽。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
string email = "fajarsyairillah@mail.com";
string Email = maskEmail(email);
Console.WriteLine("Email :"+Email);
}
public static string maskEmail(string email)
{
string pattern = @"[w-._+%a]*(?=[w]{2}@)";
string maskedEmail = System.Text.RegularExpressions.Regex.Replace(email, pattern, m => new string('*', m.Length));
return (string.IsNullOrEmpty(maskedEmail) ? email : maskedEmail);
}
}
}
这个问题有解决办法吗?
您也可以在这里使用非正则表达式方法:
public static string maskEmailNoregex(string email)
{
if (string.IsNullOrEmpty(email)) return email; // Return email back as it is null or empty
var split = email.Split('@'); // Split with @ char
if (split.GetLength(0) != 2 || split[0].Length < 5) return email; // There is nothing to modify, return email
return split[0].Substring(0, 2) + new string('*', split[0].Length-4) + split[0].Substring(split[0].Length - 2) + "@" + split[1];
}
如果您喜欢使用正则表达式,请参阅
public static string maskEmail(string email)
{
if (string.IsNullOrEmpty(email)) return email;
return Regex.Replace(email, @"(?<=^[^@]{2,})[^@](?=[^@]{2,}@)", "*");
}
请参阅C#演示。另请参阅regex演示。详细信息:
(?<=^[^@]{2,})
-字符串中的一个位置,该位置从字符串的开头开始,紧接着有两个或多个除@
之外的字符[^@]
-除@
之外的任何字符(?=[^@]{2,}@)
-字符串中的一个位置,后面紧跟除@
之外的任何两个或多个字符,直到@
字符