user2965598 user2965598 - 24 days ago 13
Java Question

Validate if input string is a number between 0-255 using 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]))"));

Answer

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

Comments