使用正则表达式验证输入字符串是否为0-255之间的数字 [英] Validate if input string is a number between 0-255 using regex

查看:45
本文介绍了使用正则表达式验证输入字符串是否为0-255之间的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将输入字符串与Regex匹配时遇到问题.我要验证输入数字在0-255之间,并且长度最多应为3个字符.代码可以正常工作,但是当我输入000000且不限长度时,显示true而不是false.

这是我的代码:-

 字符串IP ="000000000000000";System.out.println(IP.matches((0 *(?:[0-9] [0-9]?| [0-2] [0-5] [0-5]))"))); 

解决方案

您可以使用此正则表达式:

 布尔值有效= IP.matches("\\ b(1?[0-9] {1,2} | 2 [0-4] [0-9] | 25 [0-5])\\ b​​); 

RegEx演示

I am facing problem while matching input string with Regex. I want to validate input number is between 0-255 and length should be up to 3 characters long. code is working fine but when I input 000000 up to any length is shows true instead false.

Here is my code :-

String IP = "000000000000000";
        System.out.println(IP.matches("(0*(?:[0-9][0-9]?|[0-2][0-5][0-5]))"));

解决方案

You can use this regex:

boolean valid = IP.matches("\\b(1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])\\b");

RegEx Demo

这篇关于使用正则表达式验证输入字符串是否为0-255之间的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆