October 7th, 2016

PowerTip: How to detect phone numbers using regular expressions

Doctor Scripto
Scripter

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

Author

The "Scripting Guys" is a historical title passed from scripter to scripter. The current revision has morphed into our good friend Doctor Scripto who has been with us since the very beginning.

0 comments

Discussion are closed.