Is there a simple way for masking E-Mail addresses using Regular Expressions in C#
?
My E-Mail:
myawesomeuser@there.com
My goal:
**awesome****@there.com (when 'awesome' was part of the pattern)
So it's more like an inverted replacement where evertyhing that does not actually match will be replaced with *
.
Note: The domain should never be replaced!
From a performance side of view, would it make more sense to split by the @
and only check the first part then put it back together afterwards?
Note: I don't want to check if the E-Mail is valid or not. It's just a simple inverted replacement and only for my current needs, the string is an E-Mail but for sure it can be any other string as well.
Solution
After reading the comments I ended up with an extension-method for strings which perfectly matches my needs.
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;
}
which then can be called
string eMail = myawesomeuser@there.com;
string maskedMail = eMail.MaskEmail("awesome"); // **awesome****@there.com