Skip to content

Instantly share code, notes, and snippets.

@JeremyTBradshaw
Created May 17, 2023 23:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JeremyTBradshaw/2877129e7f0fdd43f94e7c3d1652f80d to your computer and use it in GitHub Desktop.
Save JeremyTBradshaw/2877129e7f0fdd43f94e7c3d1652f80d to your computer and use it in GitHub Desktop.
Regex validation for IPv4 addresses, optionally with CIDR notation
$IPRegex = @(
'^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}', #<-: 0. to 255. (x3)
'([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])', #<---------: 0 to 255
'($|/([8-9]|[1-2][0-9]|3[0-2]))$' #<-----------------------------: (optional) /8 to /32
) -join ''
$Variations = @(
# Will match:
'0.0.0.0',
'10.0.0.0/8',
'192.168.0.2/32',
'255.255.255.255',
# will not match:
'256.0.0.0',
'10.0.0.0/7',
'192.168.0.1/33'
)
$Variations | ForEach-Object { $_ -match $IPRegex }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment