Javascript regex to validate IPv4 and IPv6 address, no hostnames

前端 未结 2 1015
悲哀的现实
悲哀的现实 2020-11-30 09:35

Please suggest a single JS regex that can validate:

  • IPv4 address
  • IPv6 address

This regex should only validate address & no hostname

2条回答
  •  悲哀的现实
    2020-11-30 10:05

    I compiled these regex formulas once I could not find, in my opinion, a better solution that worked well for both IPv4 and IPv6. It does include capture groups per my own requirements but it should have no effect on it working or not.

    IPv4 Regex:

    ^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$
    

    IPv6 Regex:

    ^((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4}))*::((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4}))*|((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4})){7}$
    

    Implementation Example:

    IPv4: if ( /^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$/g.test(ipv4)) {}
    IPv6: if ( /^((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4}))*::((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4}))*|((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4})){7}$/g.test(ipv6)) {}
    

    I'm sort of an amature with Regex so feedback on my attempt would be appreciated.

提交回复
热议问题