javascript - Regular Expression for hostname & ip -


i'm trying find regex validate ip-addresses , 1 hostnames in javascript.

i looked @ many posts here , elsewhere cannot quite find 1 suits needs.

for ip found 2 work fine (dont know if there differences other format):

1: (this preferred regex 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 hostname found 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 works fine.

but^^ problem hostname regex validate

192.168.178.1111 

this not hostname, invalid ip-address.

i fit both hostname & ip regex in single regex term since hostname regex validate non-valid ip-address cannot combine them.

does have idea on how create hostname regex not validate invalid ip-address?

edit: found 1 well: http://jsfiddle.net/opd1v7au/2/

but validate example:

::2:3:4:5 

which application cannot accept.


solution: thx aaron have regex seems work (in testing @ 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 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])$ 

based on this su answer, propose modification, accepts labels starting digits except 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])$/ 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -