How to validate a domain name using Regular Expression | Java 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 ; Pattern class contains matcher ( ) method to find the matching between the given string and regular expression . ; Return if the string matched the ReGex ; Driver Code ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 :
import java . util . regex . * ; class GFG { public static boolean isValidDomain ( String str ) { String regex = " ^ ( ( ? ! - ) [ A - Za - z0-9 - ] " + " { 1,63 } ( ? < ! - ) \\ . ) " + " + [ A - Za - z ] { 2,6 } " ; Pattern p = Pattern . compile ( regex ) ; if ( str == null ) { return false ; } Matcher m = p . matcher ( str ) ; return m . matches ( ) ; } public static void main ( String args [ ] ) { String str1 = " geeksforgeeks . org " ; System . out . println ( isValidDomain ( str1 ) ) ; String str2 = " contribute . geeksforgeeks . org " ; System . out . println ( isValidDomain ( str2 ) ) ; String str3 = " - geeksforgeeks . org " ; System . out . println ( isValidDomain ( str3 ) ) ; String str4 = " geeksforgeeks . o " ; System . out . println ( isValidDomain ( str4 ) ) ; String str5 = " . org " ; System . out . println ( isValidDomain ( str5 ) ) ; } }