Finding Multiple Illegal Characters

by Oct 25, 2016

Previously, we illustrated how to use the -match operator to find illegal characters in a text. The -match operator finds only the first match, though. To list all illegal characters in a string, try this approach:

# some email address
$mail = 'THOMAS.börßen_senbÖ'
# list of legal characters, inverted by "^"
$pattern = '[^a-z0-9\.@]'

# find all matches, case-insensitive
$allMatch = [regex]::Matches($mail, $pattern, 'IgnoreCase')
# create list of invalid characters
$invalid = $allMatch.Value | Sort-Object -Unique 

'Illegal characters found: {0}' -f ($invalid -join ', ')

The result looks like this:

Illegal characters found: _, ö, ß

Twitter This Tip! ReTweet this Tip!