Identifying Special Characters

by Apr 18, 2016

If you must ensure that a string contains only a given set of characters, try this:

$text = 'tobias.weltner'
$hasOtherCharacters = $text -cmatch '[^a-zA-Z]'

"$text has illegal characters? $hasOtherCharacters"

It is really simple: In the brackets, add the characters that are legal. Whenever PowerShell now finds a character in the string that is not in this list, you receive a $true, else $false.

This example checks whether the input was a number or a dot:

$text = '12.98'
$hasOtherCharacters = $text -cmatch '[^0-9.]'

"$text has illegal characters? $hasOtherCharacters"

The result would be:

 
12.98 has illegal characters? False
 

If the text contained a comma instead of a dot, the result would be different because the comma is considered illegal:

$text = '12,98'
$hasOtherCharacters = $text -cmatch '[^0-9.]'

"$text has illegal characters? $hasOtherCharacters"
 
12,98 has illegal characters? True
 

Twitter This Tip! ReTweet this Tip!