简体   繁体   English

IP地址的正则表达式,最后一部分非零

[英]Regex for IP address with last part non-zero

This is my regex for IP address. 这是我的IP地址正则表达式。 How can I modify it to exclude a 0 (ZERO) in the last part. 我如何修改它以在最后一部分中排除0(零)。

^([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])$

Example: 例:

148.23.54.20 //valid 148.23.54.20 //有效

148.23.54.0 //Invalid 148.23.54.0 //无效

Make sure your number does not start with a zero... 确保您的电话号码不以零开头 ...

[1-9]\d?

So, for example, your regex would end with 因此,例如,您的正则表达式将以

\.([1-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$

This will allow 1 to 255. 这将允许1到255。

The extra escapes were left out for clarity. 为了清楚起见,多余的转义被省略。

Sidenote 边注

For your other 3 cases that that can be 0, simply add an option for only 0 对于其他3个可能为0的情况,只需为0添加一个选项

\.(0|[1-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])

仅特殊处理最后一部分

^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?)$

How about a non regex solution: 非正则表达式解决方案如何:

String ip = /* some ip */;
String[] bytes = ip.split("\\.");
if (!bytes[3].equals("0") && Arrays.stream(bytes).map(Integer::parseInt).allMatch(i -> i >= 0 && i < 256)) {
    //Valid ip
}

You can check for IntegerParseException and do some bounds checks if you're expecting some crazy input, as well. 您还可以检查IntegerParseException并进行边界检查(如果您还希望得到一些疯狂的输入)。 I believe this is a lot more readable and thus maintainable for that sake 我相信这更容易阅读,因此可以维护

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM