C# Mask email address for GDPR reasons
THE EXTENSION METHOD:
using System;
using System.Text.RegularExpressions;
namespace MyNamespace
{
public static class EmailMasker
{
private static string _PATTERN = @"(?<=[\w]{1})[\w-\._\+%\\]*(?=[\w]{1}@)|(?<=@[\w]{1})[\w-_\+%]*(?=\.)";
public static string MaskEmail(this string s)
{
if (!s.Contains("@"))
return new String('*', s.Length);
if (s.Split('@')[0].Length < 4)
return @"*@*.*";
return Regex.Replace(s, _PATTERN, m => new string('*', m.Length));
}
}
USAGE:
using MyNamespace;
public void TestMethod()
{
string email = "someperson@somedomain.com";
string maskedEmail = email.MaskEmail();
// result: s********n@s********n.com
}
last updated august 2018