Reputation: 441
I'm trying to find a regex to validate IP-Addresses and one for Hostnames in Javascript.
I looked at many posts here and elsewhere but cannot quite find one that suits my needs.
For the IP I found two that work fine (dont know if there are differences other than the format):
1: (this is my preferred regex for IP-Addresses)
^(?:(?: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]?)$
2:
^(([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])$
For the Hostname I found this one:
/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/
which also works fine.
BUT^^ the problem is that the hostname regex will validate
192.168.178.1111
This is not a hostname, this is an invalid IP-Address.
I would like to fit both hostname & IP regex together in a single regex term but since the hostname regex will validate any non-valid IP-Address I cannot combine them.
Does anyone have an idea on how to create a hostname regex that will not validate an invalid IP-Address?
EDIT: I found this one as well: http://jsfiddle.net/opd1v7au/2/
but this will validate for example:
::2:3:4:5
which my application cannot accept.
Solution: thx to Aaron I have this regex for now which seems to work (in testing at the moment)
^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)+([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$
Combined version to validate IP-Addresses & Hostnames ->RegExr.com:
^(?:(?: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]?)$|^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)+([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$
Upvotes: 3
Views: 8709
Reputation: 1
Based on the AAron solution, the regex with a comma separation:
/((((([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])(\/([4-9]|[12][0-9]|3[0-2]))?)([,\s]+|$))*)|(((([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)+([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])([,\s]+|$))*)/gm
Your opinion (see https://regex101.com/r/JVHcUm/1) ?
Upvotes: 0
Reputation: 24802
Based on this SU answer, I propose this modification, which accepts labels starting with digits except for the top level domain :
/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$/
Upvotes: 3