Obfuscate RRS feed

  • Question

  • Hello,

    I need to obfuscate all emails in a string. e.g:

    To replace an email "EMAIL REMOVED" by "name(at)domain(dot).com".

    I have been using the following but it only replaces @ and I am not sure if this is the best way to do this:

        public static String Obfuscate(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);
        } // Obfuscate

    I would like to be able to use replace the DOT to and maybe not using a regex would be better?

    Saturday, October 10, 2009 2:32 AM

All replies

  • Take a look at this method.
    Good coding involves knowing one's logical limits and expanding them as necessary.
    Saturday, October 10, 2009 2:57 AM
  • A regex is overkill:

    string ObfuscateEmail(string value)
        return value.Replace("@", "(at)").Replace(".", "(dot)");
    Saturday, October 10, 2009 5:27 AM
  • hi, following code will do this job. change "EMAIL REMOVED" to some email address in sampleText variable.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;
    namespace TEST
        class Program
            static void Main(string[] args)
                string sampleText = "this is a sample text. There is an email EMAIL REMOVED provided in this text. EMAIL REMOVED Thanks ";
            public static string Obfuscate(string text)
                foreach (string str in text.Split(' '))
                    if (IsEmailAddress(str.Trim()) == true)
                        text = text.Replace(str, str.Replace("@", "(at)").Replace(".", "(dot)"));
                return text;
            public static bool IsEmailAddress(string emailAddress)
                string patternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                      + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                      + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                      + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                      + @"[a-zA-Z]{2,}))$";
                Regex reStrict = new Regex(patternStrict);
                bool isStrictMatch = reStrict.IsMatch(emailAddress);
                return isStrictMatch;
    • Proposed as answer by yazeem Friday, October 16, 2009 6:15 AM
    Saturday, October 10, 2009 7:53 AM