Verifying IP addresses with Java regular expressions
•
Java
\d{1,3}\.\d{1,3}
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test22 { public static void main(String[] args) { String regex = "\\d{1,3}\\.\\d{1,3}"; String answer = "Y"; do { System.out.print("请输入 IP 地址:"); Scanner scan = new Scanner(system.in); String phone = scan.next(); // 接收用户在控制台输入的电话号码 Pattern pattern = Pattern.compile(regex); // 编译正则表达式 Matcher matcher = pattern.matcher(phone); // 创建给定输入模式的匹配器 boolean bool = matcher.matches(); if(bool) { // 如果验证通过 System.out.println("输入的 IP 地址正确。"); } else { System.out.println("输入的IP地址格式错误。"); } System.out.print("是否继续输入?(Y/N 或者 y/n)"); answer = scan.next(); }while(answer.equalsIgnoreCase("Y")); System.out.println("程序结束。"); } }
请输入 IP 地址:11.154.15.1 输入的 IP 地址正确。 是否继续输入?(Y/N 或者 y/n)y 请输入 IP 地址:22a.7.68.9 输入的IP地址格式错误。 是否继续输入?(Y/N 或者 y/n)n 程序结束。
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码