Created
May 17, 2023 23:41
-
-
Save JeremyTBradshaw/2877129e7f0fdd43f94e7c3d1652f80d to your computer and use it in GitHub Desktop.
Regex validation for IPv4 addresses, optionally with CIDR notation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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