The switch statement is the most powerful statement in the PowerShell language. This statement combines pattern matching, branching, and iteration all into a single control structure. – Bruce Payette “Windows PowerShell in Action”
Regex Switch
I’m using pattern matching, branching, and iteration. Plus I’m using the Regex switch.
function ConvertTo-PhoneNumber { param( [Parameter(Mandatory=$true)] $query ) $r = switch -Regex ( $query.ToCharArray() ) { 'a|b|c' { 2 } 'd|e|f' { 3 } 'g|h|i' { 4 } 'j|k|l' { 5 } 'm|n|o' { 6 } 'p|q|r|s' { 7 } 't|u|v' { 8 } 'w|x|y|z' { 9 } } "$r" }
Try It
ConvertTo-PhoneNumber TMobile
8 6 6 2 4 5 3





{ 6 comments… read them below or add one }
Doug, that’s one of your coolest PS functions so far, there’s so much going on in what appears to be a very simple expression.
I assume “$r” is equivalent to –> $r.toString()?
keep them coming!
-Steve
Thanks Steve.
$r is of type Object[]. Putting it in quotes, PowerShell does string concatenation.
Doug
Doug, how about this (the last replace is optional…):
function ConvertTo-PhoneNumber2 {
param(
[Parameter(Mandatory=$true)]
$query
)
$query -replace ‘[abc]‘, ’2′ `
-replace ‘[def]‘, ’3′ `
-replace ‘[ghi]‘, ’4′ `
-replace ‘[jkl]‘, ’5′ `
-replace ‘[mno]‘, ’6′ `
-replace ‘[pqrs]‘, ’7′ `
-replace ‘[tuv]‘, ’8′ `
-replace ‘[wxyz]‘, ’9′ `
-replace ‘[^0-9a-z]‘
}
Thanks for the post Chris. That works!
It’d be interesting to benchmark which approach is faster.
I like your use of brackets, []. I will update my sample to use that.
I wonder which regex is faster too, ‘a|b|c’ vs. ‘[abc]‘.
Doug
I also added one line so it also accepts numbers !
function ConvertTo-PhoneNumber2 {
param([Parameter(Mandatory=$true)]
$query
)
$query -replace ‘[abc]‘, ’2′ `
-replace ‘[def]‘, ’3′ `
-replace ‘[ghi]‘, ’4′ `
-replace ‘[jkl]‘, ’5′ `
-replace ‘[mno]‘, ’6′ `
-replace ‘[pqrs]‘, ’7′ `
-replace ‘[tuv]‘, ’8′ `
-replace ‘[wxyz]‘, ’9′ `
-replace ‘[0-9]‘, “$_” `
-replace ‘[^0-9a-z]‘
}
#Benchmark
$( 0..500 | Measure-Command { ConvertTo-PhoneNumber 555dontcall } ).ticks
#9793984
$( 0..500 | Measure-Command { ConvertTo-PhoneNumber2 555dontcall } ).ticks
#1084970
Great solution.
Thank you both
oh heck.
The addition I made ( -replace ‘[0-9]‘, “$_” ` ) proved to be totally useless and causes invalid results !
I’ve noticed that after my previous reply.
However after removing my line, the benchmark data is still valid, so the number of ticks still stand.
I’m sorry for the mishap. :blush: