Validating an IPv4 address using a regular expression is not necessarily a trivial task.
The IP address consists of four octets; each octet can be a value between 0 and 255. When using a regular expression, the values are considered to be strings, therefore the following strings must be considered:
- [0-9]: 0 to 9
- [1-9][0-9]: 1 to 9, then 0 to 9 (10 to 99)
- 1[0-9]{2}: 1, then 0 to 9, then 0 to 9 (100 to 199)
- 2[0-4][0-9]: 2, then 0 to 4, then 0 to 9 (200 to 249)
- 25[0-5]: 2, then 5, then 0 to 5 (250 to 255)
Each of these is an exclusive set, so alternation is used to merge all of the previous small expressions into a single expression. This generates the following group that matches a single octet (0 to 255):
([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])
IP address validation contains repetition now; four octets with a period between each:
(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])
There are other, perhaps better, ways than such a long regex. If a string is a strong candidate for being an IP address, consider using the TryParse static method on the IPAddress type. It will handle both v4 and v6 addressing:
$ipAddress = [IPAddress]0 # Used as a placeholder
if ([IPAddress]::TryParse("::1", [ref]$ipAddress)) {
$ipAddress
}
$ipAddress = [IPAddress]0 # Used as a placeholder
if ([IPAddress]::TryParse("::1", [ref]$ipAddress)) {
$ipAddress
}