Home > Java > Javagetting Started > How to determine whether a string is an IP address in java

How to determine whether a string is an IP address in java

王林
Release: 2020-08-06 16:07:37
forward
4261 people have browsed it

How to determine whether a string is an IP address in java

要实现该算法我们首先应该知道,IP地址应该依据哪些条件:

(推荐教程:java入门教程

判断原则:

  • 判断该字符长度是否是7-15位之间(0.0.0.0-255.255.255.255.255)

  • 是否能以小数点分成四段

  • 每段是否都是数字

  • 每段数字是否都在0-255之间

只有以上四个条件都满足了,才是IP的正确格式。

实现该算法有两种比较简单的方法,一种是常规判断,另一种是利用正则表达式进行判断,下面以函数的形式实现这两种方法,可以直接复制函数使用,传入的参数是待判断的字符串,返回的是布尔变量。

(视频教程推荐:java视频教程

常规方法判断

//判断字符是否是IP
public boolean isCorrectIp(String ipString) {
        //1、判断是否是7-15位之间(0.0.0.0-255.255.255.255.255)
	if (ipString.length()<7||ipString.length()>15) {
		return false;
	}
	//2、判断是否能以小数点分成四段
	String[] ipArray = ipString.split("\\.");		
	if (ipArray.length != 4) {
		return false;
	}
	for (int i = 0; i < ipArray.length; i++) {
		//3、判断每段是否都是数字
		try {
			int number = Integer.parseInt(ipArray[i]);
			//4.判断每段数字是否都在0-255之间
			if (number <0||number>255) {
        			return false;
			}
		} catch (Exception e) {
			return false;
		}
	}		
	return true;
	}
Copy after login

正则表达式方法判断

//利用正则表达式判断字符是否为IP
public boolean isCorrectIp2(String ipString) {
	String ipRegex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";	//IP地址的正则表达式
	//如果前三项判断都满足,就判断每段数字是否都位于0-255之间
	if (ipString.matches(ipRegex)) {
		String[] ipArray = ipString.split("\\.");
		for (int i = 0; i < ipArray.length; i++) {
			int number = Integer.parseInt(ipArray[i]);
			//4.判断每段数字是否都在0-255之间
			if (number <0||number>255) {
				return false;
			}
		}
		return true;
	}
	else {
		return false;	//如果与正则表达式不匹配,则返回false
	}	
}
Copy after login

测试结果:

How to determine whether a string is an IP address in java

The above is the detailed content of How to determine whether a string is an IP address in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template