How to validate an IP address using ReGex | Python3 program to validate IP address using Regex ; Function for Validating IP ; Regex expression for validating IPv4 ; Regex expression for validating IPv6 ; Checking if it is a valid IPv4 addresses ; Checking if it is a valid IPv6 addresses ; Return Invalid ; IP addresses to validate
import re NEW_LINE def Validate_It ( IP ) : NEW_LINE INDENT regex = " ( ( [ 0-9 ] ▁ [ 1-9 ] [ 0-9 ] ▁ 1[0-9 ] [ 0-9 ] ▁ " \ "2[0-4 ] [ 0-9 ] ▁ 25[0-5 ] ) \\ . ) { 3 } " " ( [0-9 ] ▁ [ 1-9 ] [ 0-9 ] ▁ 1[0-9 ] [ 0-9 ] ▁ " \ "2[0-4 ] [ 0-9 ] ▁ 25[0-5 ] ) " NEW_LINE regex1 = " ( ( ( [0-9a - fA - F ] ) { 1,4 } ) \\ : ) { 7 } " p = re . compile ( regex ) NEW_LINE p1 = re . compile ( regex1 ) NEW_LINE if ( re . search ( p , IP ) ) : NEW_LINE INDENT return " Valid ▁ IPv4" NEW_LINE DEDENT elif ( re . search ( p1 , IP ) ) : NEW_LINE INDENT return " Valid ▁ IPv6" NEW_LINE DEDENT return " Invalid ▁ IP " NEW_LINE DEDENT IP = "203.120.223.13" NEW_LINE print ( Validate_It ( IP ) ) NEW_LINE IP = " fffe : 3465 : efab : 23fe : 2235:6565 : aaab : 0001" NEW_LINE print ( Validate_It ( IP ) ) NEW_LINE IP = "2F33:12a0:3Ea0:0302" NEW_LINE print ( Validate_It ( IP ) ) NEW_LINE