Monthly Archive

Categories

Test if string contains numeric

How can you test if a string contains a numeric character?

The simple answer is to use a regular expression. If you’ve been reading my stuff for any length of time you’ll know how much I love regular expressions. This is a simple regex.

Create a string

PS> $s1 = 'qwertyuiop'

Test if it has numerics

PS> $s1 -match '\d'
False

if you use D you’re testing for non numeric characters
PS> $s1 -match '\D'
True

 

Lets add a numeric to confirm

PS> $s2 = 'qwert6yuiop'
PS> $s2 -match '\d'
True

This time we get a positive result

The test for non numerics still works
PS> $s2 -match '\D'
True

 

Comments are closed.