Replace email

S

shapper

Hello,

I need to obfuscate all emails (with anchor tag or simple text) in a
string:
String html = "<p>This is a text email (e-mail address removed) an
this one is an anchor <a href=\"mailto:[email protected]
\">[email protected]</a>email.</p>";

I have a Regex that I use to validate email addresses so I think I
could use it to identify email addresses in a string and replace the @
by (AT) and . by (DOT):

@"^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+
\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.))
{0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-
Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|
2[0-4]\d|25[0-5])\]))$";

How can I do this?

Thanks,
Miguel
 
S

shapper

I was able to solve it with the following extension:

public static String ObfuscateEmails(this String text, String at)
{

Regex expression = new Regex(@"\b(?<start>[a-z0-9!#$%&'*+/=?^_`
{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*)@(?<end>(?:[a-z0-9](?:[a-
z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|
name|aero|jobs|museum))\b", RegexOptions.IgnoreCase);
String fix = String.Concat("${start}", at, "${end}");
return text == null ? null : expression.Replace(text, @fix);

} // ObfuscateEmails

Not sure if it is the best way but it works.

Thanks,
Miguel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top