13

Quick Tip - Detecting Special Characters In A String The Easy Way

 3 years ago
source link: https://thomasrayner.ca/quick-tip-detecting-special-characters-in-a-string-the-easy-way/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Quick Tip - Detecting Special Characters In A String The Easy Way

Here’s a super easy way to detect special characters in a string. Consider the following.

$string1 = 'something'
$string2 = 'some@thing'

$string1 -eq $($string1 -replace '[^a-zA-Z]','')
$string2 -eq $($string2 -replace '[^a-zA-Z]','')

String1 has no special characters, String2 does. All I’m doing is comparing the string to “the string if we replace everything that isn’t a regular letter” using the -replace operator.

It’s just that easy.

You could do the same thing with the -match operator, too. The point here is looking at the regex.

$string -match '[^a-zA-Z]'
Written on March 9, 2016

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK