i have an issue, i have to apply masking/hiding part of email address in c#. example
[email protected]==> jh**[email protected]
[email protected]==> bi****[email protected]
[email protected]==>br*******[email protected]
i have this code but its giving exception for some emails. "Index was outside the bounds of the array."
for (int i = 0; i < eml.Length; i++)
{
int j = i == (eml.Length - 1) ? 0 : 1;
cc = eml[i].ToString();
if (i <= 1)
{
dispeml += cc;
}
else
if (eml[i + (j + k)].ToString() == "@")
{
dispeml += cc;
k = 0;
fl = 1;
}
else
if (eml[i + j].ToString() == "@")
{
dispeml += cc;
fl = 1;
}
else
if (fl == 1)
{
dispeml += cc;
}
else
{
dispeml += "*";
}
}
Here is a approach to solve this with Regex
string input = "[email protected]";
string pattern = @"(?<=[\w]{1})[\w-\._\+%]*(?=[\w]{1}@)";
string result = Regex.Replace(input, pattern, m => new string('*', m.Length));
//j**[email protected]
Explanation:
(?<=[\w]{1})
the name has to start with 1 word-character
[\w-\._\+%]*
the replacement-part can contain 0-n word characters including -_.+%
(?=[\w]{1}@)
the name has to end with one word character followed by a @
Depending on the amount of characters you want to remain unchanged you can change {1}
to {2}
or something else at the beginning or at the end.