Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell SWITCH and REGEX

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}'})
   {}
}
like image 270
Jan Girke Avatar asked Oct 17 '25 06:10

Jan Girke


2 Answers

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
   }
}
like image 121
Mathias R. Jessen Avatar answered Oct 20 '25 08:10

Mathias R. Jessen


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" }
}
like image 29
Janne Tuukkanen Avatar answered Oct 20 '25 08:10

Janne Tuukkanen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!