How to validate a domain name using Regular Expression | Python3 program to validate domain name using regular expression ; Function to validate domain name . ; Regex to check valid domain name . ; Compile the ReGex ; If the string is empty return false ; Return if the string matched the ReGex ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 :
import re NEW_LINE def isValidDomain ( str ) : NEW_LINE INDENT regex = " ^ ( ( ? ! - ) [ A - Za - z0-9 - ] " + NEW_LINE INDENT " { 1,63 } ( ? < ! - ) \\ . ) " + NEW_LINE DEDENT p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( p , str ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT str1 = " geeksforgeeks . org " NEW_LINE print ( isValidDomain ( str1 ) ) NEW_LINE str2 = " contribute . geeksforgeeks . org " NEW_LINE print ( isValidDomain ( str2 ) ) NEW_LINE str3 = " - geeksforgeeks . org " NEW_LINE print ( isValidDomain ( str3 ) ) NEW_LINE str4 = " geeksforgeeks . o " NEW_LINE print ( isValidDomain ( str4 ) ) NEW_LINE str5 = " . org " NEW_LINE print ( isValidDomain ( str5 ) ) NEW_LINE