Last active
August 29, 2015 14:17
-
-
Save michaelhidalgo/f46a49e941179ec63fe4 to your computer and use it in GitHub Desktop.
Regular Expression TLD email
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Globalization; | |
using FluentSharp.CoreLib; | |
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
using System.Text.RegularExpressions; | |
namespace RegExTest | |
{ | |
[TestClass] | |
public class RegExTest | |
{ | |
private const string RegExPattern =@"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + | |
@"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$"; | |
private const int MaxIterations = 100000; | |
[TestMethod] | |
public void Email_Unicode_TLD() | |
{ | |
string input = "admin@استفتاء.مصر"; | |
//REplacing unicode TLD https://msdn.microsoft.com/en-us/library/01escwtf%28v=vs.110%29.aspx | |
input = Regex.Replace(input, @"(@)(.+)$",this.DomainMapper,RegexOptions.None, TimeSpan.FromMilliseconds(200)); | |
Assert.AreEqual(input,"[email protected]"); | |
Assert.IsTrue(Regex.IsMatch(input, RegExPattern,RegexOptions.None,TimeSpan.FromSeconds(1))); | |
} | |
[TestMethod] | |
public void Email_Long_TLD_Is_Supported() | |
{ | |
const string input = "[email protected]"; | |
var result = Regex.IsMatch(input, RegExPattern, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1)); | |
Assert.IsTrue(result); | |
} | |
[TestMethod] | |
public void Email_Is_Valid() | |
{ | |
const string input = "[email protected]"; | |
var result = Regex.IsMatch(input, RegExPattern, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1)); | |
Assert.IsTrue(result); | |
} | |
[TestMethod] | |
public void Email_Is_Invalid() | |
{ | |
const string input = "mhidalgo"; | |
var result = Regex.IsMatch(input, RegExPattern, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1)); | |
Assert.IsFalse(result); | |
} | |
[TestMethod] | |
public void FuzzInput() | |
{ | |
for (int x = 0; x < MaxIterations; x++) | |
{ | |
//Generates a random input of 50 characters per iteration | |
var fuzzString = 10.randomChars() + "".random_Email() + 15.randomChars(); | |
Assert.IsTrue(fuzzString.Length == 50); | |
Regex.IsMatch(fuzzString,RegExPattern,RegexOptions.IgnoreCase,TimeSpan.FromSeconds(1)); | |
} | |
} | |
private string DomainMapper(Match match) | |
{ | |
// IdnMapping class with default property values. | |
var idn = new IdnMapping(); | |
string domainName = match.Groups[2].Value; | |
try | |
{ | |
domainName = idn.GetAscii(domainName); | |
} | |
catch (ArgumentException) | |
{ | |
} | |
return match.Groups[1].Value + domainName; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment