Programming

IP 주소 형식 체크 정규식

nineDeveloper 2020. 3. 27.
728x90

문자열이 IP(0.0.0.0 ~ 255.255.255.255) 범위 안에 있는지 확인하기 위한 정규 표현식.

Java

String ip1 = "127.0.0.1";
String ip2 = "255.255.255.255";
String ip3 = "255.255.255.256";

String ipRegex = "(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])";

System.out.println(ip1.matches(ipRegex));
System.out.println(ip2.matches(ipRegex));
System.out.println(ip3.matches(ipRegex));

Validation

@Pattern(regexp="(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])", message="IP 주소 형식이 올바르지 않습니다")
private String ip;
728x90

댓글

💲 추천 글