在Java中验证IPv4字符串
- 论坛
- 在Java中验证IPv4字符串
23 浏览
在Java中验证IPv4字符串
以下方法用于验证字符串是否为正确的IPv4地址,如果有效则返回true。对于正则表达式和优雅性方面的任何改进都将非常感谢:
public static boolean validIP(String ip) { if (ip == null || ip.isEmpty()) return false; ip = ip.trim(); if ((ip.length() < 6) & (ip.length() > 15)) return false; try { Pattern pattern = Pattern.compile("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"); Matcher matcher = pattern.matcher(ip); return matcher.matches(); } catch (PatternSyntaxException ex) { return false; } }