Algorithm question: Determine whether the string is a legal ipv4 address

Problem description
Determine whether the string is a legal ipv4 address

Features of ipv4 address For
example, 123.1.33.2
has four digits, and each digit is directly divided by. The range of each digit is 0-255, that is, between 0.0.0.0 and 255.255.255.255

(Method 1)
Divide the current string into an array of characters (note the delimiter. It needs to be escaped and written as \\.), and then judge whether the range of each bit is between 0-255, if it is between 0-255, judge Whether the current character ends with 0 and is not the first digit (for example, 01.11.11.11 is not a legal ipv4 address)

boolean checkIp(String ip) throws Exception{
    
    

		String arrs[]=ip.split("\\.");//.转义
		if (arrs.length!=4) {
    
    

			return false;
		}
		for(int i=0;i<arrs.length;i++) {
    
    
			Integer num=null;
			try {
    
    
				num=Integer.parseInt(arrs[i]);
				if (num<0||num>255) {
    
    
					return false;
				}
				if (!num.equals("0")&&arrs[i].startsWith("0")) {
    
    //避免01出现
					return false;
				}
				
			} catch (NumberFormatException e) {
    
    
				// TODO: handle exception
				return false;
			}
		}
		return true;
		
	}

(Method 2) Use regular expressions

boolean checkIp2(String ip) throws Exception{
    
    

		String arrs[]=ip.split("\\.");//.转义
		if (arrs.length!=4) {
    
    

			return false;
		}
		String reg="\\d||[1,9]\\d{1,2}";
		for(String arr:arrs) {
    
    
			try {
    
    
				if (!arr.matches(reg)||Integer.parseInt(arr)>255) {
    
    
					return false;	
				}
			} catch (NumberFormatException e) {
    
    
				// TODO: handle exception
			}
		}
		return true;
		
	}

Guess you like

Origin blog.csdn.net/rj2017211811/article/details/105698956