This is a comprehensive IPv6 regular expression that tests all the valid IPv6 text notations (expanded, compressed, expanded-mixed, compressed-mixed) with an optional prefix length. It will also capture the various parts into capture groups. You can skip the capture groups by putting a ?: right after the opening paren for a capture group.
This is the regular expression I created and use in my IPvX IP calculator for both IPv4 and IPv6.
^# Anchor (# BEGIN Compressed-mixed *** Group 1 *** (# BEGIN Hexadecimal Notation *** Group 2 *** (?: (?:[0-9A-F]{1,4}:){5}[0-9A-F]{1,4} # No :: | (?:[0-9A-F]{1,4}:){4}:[0-9A-F]{1,4} # 4::1 | (?:[0-9A-F]{1,4}:){3}(?::[0-9A-F]{1,4}){1,2} # 3::2 | (?:[0-9A-F]{1,4}:){2}(?::[0-9A-F]{1,4}){1,3} # 2::3 | [0-9A-F]{1,4}:(?::[0-9A-F]{1,4}){1,4} # 1::4 | (?:[0-9A-F]{1,4}:){1,5} # :: End | :(?::[0-9A-F]{1,4}){1,5} # :: Start | : # :: Only ): )# END Hexadecimal Notation (# BEGIN Dotted-decimal Notation *** Group 3 *** (25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\. # 0 to 255. *** Group 4 *** (25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\. # 0 to 255. *** Group 5 *** (25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\. # 0 to 255. *** Group 6 *** (25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]) # 0 to 255 *** Group 7 *** )# END Dotted-decimal Notation )# END Compressed-mixed | (# BEGIN Compressed *** Group 8 *** (?:# BEGIN Hexadecimal Notation (?:[0-9A-F]{1,4}:){7}[0-9A-F]{1,4} # No :: | (?:[0-9A-F]{1,4}:){6}:[0-9A-F]{1,4} # 6::1 | (?:[0-9A-F]{1,4}:){5}(?::[0-9A-F]{1,4}){1,2} # 5::2 | (?:[0-9A-F]{1,4}:){4}(?::[0-9A-F]{1,4}){1,3} # 4::3 | (?:[0-9A-F]{1,4}:){3}(?::[0-9A-F]{1,4}){1,4} # 3::4 | (?:[0-9A-F]{1,4}:){2}(?::[0-9A-F]{1,4}){1,5} # 2::5 | [0-9A-F]{1,4}:(?::[0-9A-F]{1,4}){1,6} # 1::6 | (?:[0-9A-F]{1,4}:){1,7}: # :: End | :(?::[0-9A-F]{1,4}){1,7} # :: Start | :: # :: Only ) # END Hexadecimal Notation )# END Compressed (?:# BEGIN Optional Length /(12[0-8]|1[0-1][0-9]|[1-9]?[0-9]) # /0 to /128 *** Group 9 *** )? # END Optional Length $# Anchor
Bonus IPv4 regular expression:
^# Anchor (?:# BEGIN Dotted-decimal Notation (25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\. # 0 to 255. *** Group 1 *** (25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\. # 0 to 255. *** Group 2 *** (25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\. # 0 to 255. *** Group 3 *** (25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]) # 0 to 255 *** Group 4 *** ) # END Dotted-decimal Notation (?:# BEGIN Optional Length /(3[0-2]|[1-2]?[0-9]) # /0 to /32 *** Group 5 *** )? # END Optional Length $# Anchor
use SomeModuleor you got to CPAN, download the module and do a copy and paste.