Skip to content

Instantly share code, notes, and snippets.

@sean-m
Last active August 1, 2019 17:29
Show Gist options
  • Save sean-m/6085e96b918b4791742d7d6a34200b78 to your computer and use it in GitHub Desktop.
Save sean-m/6085e96b918b4791742d7d6a34200b78 to your computer and use it in GitHub Desktop.
RegexUtility.IsValidEmail MSDN example as PowerShell
Add-Type -Language CSharp -TypeDefinition @"
using System;
using System.Globalization;
using System.Text.RegularExpressions;
public static class RegexUtilities
{
// Examines the domain part of the email and normalizes it.
private static string DomainMapper(Match match)
{
// Use IdnMapping class to convert Unicode domain names.
var idn = new IdnMapping();
// Pull out and process domain name (throws ArgumentException on invalid)
var domainName = idn.GetAscii(match.Groups[2].Value);
return match.Groups[1].Value + domainName;
}
public static bool IsValidEmail(string email)
{
if (string.IsNullOrWhiteSpace(email)) { return false; }
try {
// Normalize the domain
email = Regex.Replace(email, @"(@)(.+)$", DomainMapper, RegexOptions.None, TimeSpan.FromMilliseconds(200));
}
catch (RegexMatchTimeoutException) {
return false;
}
catch (ArgumentException) {
return false;
}
try {
return Regex.IsMatch(email,
@"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
@"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
}
catch (RegexMatchTimeoutException) {
return false;
}
}
}
"@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment