Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate if input string is a number between 0-255 using regex

Tags:

java

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]))"));
like image 920
user2965598 Avatar asked Jul 28 '15 18:07

user2965598


People also ask

How do I match a range of numbers in regex?

With regex you have a couple of options to match a digit. You can use a number from 0 to 9 to match a single choice. Or you can match a range of digits with a character group e.g. [4-9]. If the character group allows any digit (i.e. [0-9]), it can be replaced with a shorthand (\d).

How do you write an IF condition in regex?

If the if part evaluates to true, then the regex engine will attempt to match the then part. Otherwise, the else part is attempted instead. The syntax consists of a pair of parentheses. The opening bracket must be followed by a question mark, immediately followed by the if part, immediately followed by the then part.

How can you check if a string is a number by using regular expression?

Using Regular Expressionregex = "[0-9]+"; Match the given string with Regular Expression. In Java, this can be done by using Pattern. matcher().

What regex will find letters between two numbers?

You can use regex (. *\d)([A-Z])(\d. *) - This will give you exact ONE Alphabet between numbers.


2 Answers

You can use this pattern which matches "0", "1", ... "255":

"([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"

Demo on Ideone

like image 165
Salman A Avatar answered Sep 18 '22 10:09

Salman A


Tested this:

static String pattern = "^(([0-1]?[0-9]?[0-9]?|2[0-4][0-9]|25[0-5])\\.){3}([0-1]?[0-9]?[0-9]?|2[0-4][0-9]|25[0-5]){1}$";

It works for the following:

  • IP Addresses xxx.xxx.xxx.xxx / xx.xx.xx.xx / x.x.x.x / mix of these.
  • Leading zeros are allowed.
  • Range 0-255 / maximum 3 digts.
like image 38
Leo Avatar answered Sep 21 '22 10:09

Leo