PowerShell for Windows Admins

Nov 30 2018   6:00AM GMT

Test if string contains numeric

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

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

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: