This example include java code to check whether a given www domain or a host name string is a valid domain or not. You can see code comments for detail explanation.
1. Check Valid Domain Example
/* * addStr : A domain string. * return : true means addStr is a valid domain name, false means addStr is not a valide domain name. * */ public static boolean isValidDomain(String addStr) { boolean ret = true; if("".equals(addStr) || addStr==null) { ret = false; }else if(addStr.startsWith("-")||addStr.endsWith("-")) { ret = false; }else if(addStr.indexOf(".")==-1) { ret = false; }else { // Split domain into String array. String domainEle[] = addStr.split("\\."); int size = domainEle.length; // Loop in the domain String array. for(int i=0;i<size;i++) { // If one domain part string is empty, then reutrn false. String domainEleStr = domainEle[i]; if("".equals(domainEleStr.trim())) { return false; } } // Get domain char array. char[] domainChar = addStr.toCharArray(); size = domainChar.length; // Loop in the char array. for(int i=0;i<size;i++) { // Get each char in the array. char eleChar = domainChar[i]; String charStr = String.valueOf(eleChar); // If char value is not a valid domain character then return false. if(!".".equals(charStr) && !"-".equals(charStr) && !charStr.matches("[a-zA-Z]") && !charStr.matches("[0-9]")) { ret = false; break; } } } return ret; }
2. Check Valid HostName Example
/* * This method is used to verify whether hostName is valid or not. * hostName : Given host name being checked. * return : true means hostName is valid, false means hostName is not valid. * */ public static boolean isValidHostName(String hostName) { boolean ret = true; if(hostName==null) { return false; } hostName = hostName.trim(); if("".equals(hostName) || hostName.indexOf(" ")!=-1) { ret = false; }else { // Use regular expression to verify host name. Pattern p = Pattern.compile("[a-zA-Z0-9\\.\\-\\_]+"); Matcher m = p.matcher(hostName); ret = m.matches(); if(ret) { String tmp = hostName; if(hostName.length()>15) { tmp = hostName.substring(0, 15); } // Use another regular expression to verify the first 15 charactor. p = Pattern.compile("((.)*[a-zA-Z\\-\\_]+(.)*)+"); m = p.matcher(tmp); ret = m.matches(); } } return ret; }
bullshit