Reputation: 156
Hi can anybody help me I am stuck and can't get regex to work with powershell and a switch statement. Could not find anything on the web that was helpful either.
How can I filter an IP for example or a string of 7 to 8 numbers?
switch -regex ($buffer)
{
($buffer -match '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')
{}
($buffer -match {'\d{7,8}'})
{}
}
Upvotes: 4
Views: 10075
Reputation: 174690
When used in -regex
mode, PowerShell expects the case condition to be a regex pattern, nothing else:
switch -regex ($buffer)
{
'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
{
# looks kinda like an IP
}
'\d{7,8}'
{
# just numbers
}
}
Upvotes: 9
Reputation: 1660
Use braces instead of parenthesis, and omit the variable for switch altogether:
switch (1)
{
{ $buffer -match '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' }
{ Write-Output "IP Address" }
{ $buffer -match '\d{7,8}' }
{ Write-Output "7-8 digits" }
}
Upvotes: 1