PowerTip: How to detect phone numbers using regular expressions


Summary: Cloud and Datacenter Management MVP, Thomas Rayner, shows how to use regex to detect if a string is a phone number.

Hey, Scripting Guy! Question I have an array like $phoneornot = @('780-123-4567', '780 321 6548', 'notme', 'this is 2 num'), and I need to know which array items are phone numbers. How can I do this?

Hey, Scripting Guy! Answer You can compare each item in the array with all its non-digit characters removed and see if that matches your requirements for a phone number. Here in Canada, our phone numbers are 10 digits. Here is an example:

$phones = [regex]::matches(($phoneornot -replace '\D', ''),'\b(\d{10})\b')

$phones.value

The Doctor

Comments (0)

Skip to main content