Skip to content

Instantly share code, notes, and snippets.

@bixb0012
Last active April 2, 2021 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bixb0012/1fa1cdc79e5ce92011d20e821b91076c to your computer and use it in GitHub Desktop.
Save bixb0012/1fa1cdc79e5ce92011d20e821b91076c to your computer and use it in GitHub Desktop.
PowerShell: Regular Expressions
#Requires -Version 5.1
# Reference: 1) https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_regular_expressions
# Reference: 2) https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference
$TestEmailFrom = @(
"smokey.bear@usda.gov"
" smokey.bear@usda.gov "
"<smokey.bear@usda.gov>"
" < smokey.bear@usda.gov > "
"Smokey Bear <smokey.bear@usda.gov>"
"Smokey Bear smokey.bear@usda.gov"
"Smokey Bear <smokey+fire@usda.gov>"
"Bear <bear@usda.gov>"
"Bear<bear@usda.gov>"
"Bear < bear@usda.gov > "
"Smokey's Bear <smokey's.bear@usda.gov>"
"Smokey's Bear-Owl <smokey's.bear-owl@usda.gov>"
"S. Bear <s.bear@usda.gov>"
"S.S Bear <s.s.bear@usda-home.gov>"
"Smokey Bear <smokey-w-bear@usda.gov>"
" Smokey Bear <smokey-w-bear@usda.gov>"
)
# Example 1: E-mail address validation and parsing
# Adapted from https://www.emailregex.com to add subaddressing tag
$EmailAddressRegex = @(
"^\s*" # BOL
"(?<LocalPart>\w+(?:[._\-']\w+)*)+" # local-part
"(?:\+(?<Tag>\w+(?:[._\-']\w+)*))?" # subaddressing tag
"@(?<Domain>(?:\w+(?:[-.]\w+)*)+\.(?:\w{2,}))" # domain
"\s*$" # EOL
)
# Example 2: E-mail From (name and address) validation and parsing
$EmailFromRegex = @(
"^\s*" # BOL
"(?:(?<FirstName>\w+(?:[.\-'][\s\w]+?)*?)\s*" # first name
"(?<LastName>\w+(?:[.\-'][\s\w]+?)*?)?\s*)??" # last name
"<?\s*?(?<LocalPart>\w+(?:[._\-']\w+)*)+" # local-part
"(?:\+(?<Tag>\w+(?:[._\-']\w+)*))?" # subaddressing tag
"@(?<Domain>(?:\w+(?:[-.]\w+)*)+\.(?:\w{2,}))+\s*?>?" # domain
"\s*$" # EOL
)
# Example 3: Phone number validation and parsing, North American Numbering Plan
# Adapted from Francis Gagnon at https://stackoverflow.com/questions/16699007/regular-expression-to-match-standard-10-digit-phone-number
$PhoneNanpRegex = @(
"^\s*" # BOL
"(?:\+?(?<CountryCode>\d{1,3}))?[-. (]*" # country code
"(?<AreaCode>\d{3})[-. )]*" # area code
"(?<Prefix>\d{3})[-. ]*" # central office code/prefix
"(?<LineNumber>\d{4})" # line number
"(?: *x(?<Extension>\d+))?" # extension
"\s*$" # EOL
)
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment