IP Address Regex – CodePal
# Regex for validating IP addresses
Here is an example of a regular expression that can match both IPv4 and IPv6 addresses:
### A possible regex
“`
^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|(?:(?:(?:[0-9a-fA-F]){1,4}:){7}(?:[0-9a-fA-F]){1,4})$
“`
### Regex Breakdown
“`
^ # Matches the start of the string
(?: # Non-capturing group for IPv4 addresses
(?: # Non-capturing group for each octet
25[0-5] # Matches 250-255
| # Or
2[0-4][0-9] # Matches 200-249
| # Or
[01]?[0-9][0-9]? # Matches 0-199
)
\. # Matches a dot
){3} # Repeats the previous group 3 times
(?: # Non-capturing group for the last octet of IPv4 addresses
25[0-5] # Matches 250-255
| # Or
2[0-4][0-9] # Matches 200-249
| # Or
[01]?[0-9][0-9]? # Matches 0-199
)
| # Or
(?: # Non-capturing group for IPv6 addresses
(?: # Non-capturing group for each hextet
(?:[0-9a-fA-F]){1,4} # Matches 1-4 hexadecimal characters
: # Matches a colon
){7} # Repeats the previous group 7 times
(?:[0-9a-fA-F]){1,4} # Matches 1-4 hexadecimal characters
)
$ # Matches the end of the string
“`
Examples of strings that should match this regular expression are:
– `192.168.4.81`
– `192.168.4.197`
– `fd46:3abc:f3dd:30da:490:db13:20ea:1a8e`
– `fd46:3abc:f3dd:30da:14c9:45ee:6895:f4f0`
### Final notes
Note that this regular expression is not perfect and may not match all valid IP addresses, but it can be a good starting point. Also, this regular expression does not check if the IP address is reserved or private, which may be important in some cases.
Read more here: Source link
