gpt4 book ai didi

java代码获取ip地址类

转载 作者:行者123 更新时间:2023-11-30 03:39:20 26 4
gpt4 key购买 nike

我编写这段代码是为了要求用户输入一个IP地址,它使用正则表达式工作,但后来我想告诉用户这个IP属于哪个类别,具体取决于范围(0-126)A类,(128- 191)b类,(192-224)c类,127是一个异常“环回”,我不知道该怎么做,有人可以帮忙吗?

这是我的代码:

public class main {


public static void main(String[]args){

String IP="";
Scanner Scr = new Scanner(System.in);
System.out.println("Enter a valid network IP:");
// thanks to this link http://www.mkyong.com/regular-expressions/how-to-validate-ip-address-with-regular-expression/
String pattern = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
//String pattern = "[0-255][.][0-255][.][0-255][.][0-255]";
boolean matches = false;
do{

IP = Scr.nextLine();
matches = Pattern.matches(pattern, IP);
if(matches==false)
System.out.println("wrong range");
}while(!matches);

Scr.close();
}
}

最佳答案

您使用的正则表达式包含 capturing groups 。您可以使用它们来提取第一个数字组,然后将其转换为 int 并使用它来决定需要打印的内容。

您需要一个 Pattern 对象,而不是静态 Pattern.matches 方法,该对象可用于为以下对象创建 Matcher一个特定的字符串。该权限允许访问捕获组。

您的代码最终可能如下所示:

    Pattern pattern = Pattern.compile("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
boolean matches = false;
do {
IP = Scr.nextLine();
Matcher matcher = pattern.matcher(IP);
matches = matcher.matches();
if (matches == false)
System.out.println("wrong range");
else {
int number = Integer.parseInt(matcher.group(1));
System.out.println("first group is " + number);
if (number < 127)
System.out.println("Class A");
else ...
...

关于java代码获取ip地址类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27139010/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com