4

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}'})
   {}
}
0

2 Answers 2

10

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
   }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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" }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.