1

Using this as a guide to attempt to emulate an if-else Java regex, I came up with: [0-2]?(?:(?<=2)(?![6-9])|(?<!2)(?=[0-9])) to do the following:

An optional digit between 0-2 inclusive as the leftmost digit; However, if the first digit is a 2, then the next digit to the right can be maximum 5. If it is a 0 or 1, or left blank, then 0-9 is valid. I am trying to ultimately end up allowing a user to only write the numbers 0-255.

Testing the regular expression on both Regex101 as well as javac doesn't work on test cases, despite the Regex101 explanation being congruent with what I want.

When I test the regex:

System.out.println("0".matches("[0-2]?(?:(?<=2)(?![6-9])|(?<!2)(?=[0-9]))")); ---> false

System.out.println("2".matches("[0-2]?(?:(?<=2)(?![6-9])|(?<!2)(?=[0-9]))")); ----> true

System.out.println("25".matches("[0-2]?(?:(?<=2)(?![6-9])|(?<!2)(?=[0-9]))")); ----> false

System.out.println("22".matches("[0-2]?(?:(?<=2)(?![6-9])|(?<!2)(?=[0-9]))")); ----> false

System.out.println("1".matches("[0-2]?(?:(?<=2)(?![6-9])|(?<!2)(?=[0-9]))")); ----> false

It appears so far, from few test cases, 2 is the only valid case that is accepted by the regex.

For reference, here is my initial regex, using if-else that limits a number to the range of 0-255: [0-2]?(?(?<=2)[0-5]|[0-9])(?(?<=25)[0-5]|[0-9])

Community
  • 1
  • 1
Abdul
  • 997
  • 2
  • 19
  • 37

2 Answers2

2

I don't see why to mimic if else for checking a range. It's just putting some patterns together.

^(?:[1-9]?\d|1\d\d|2[0-4]\d|25[0-5])$
  • ^ start anchor
  • (?: opens a non capture group for alternation
  • [1-9]?\d matches 0-99
  • 1\d\d matches 100-199
  • 2[0-4]\d matches 200-249
  • 25[0-5] matches 250-255
  • $ end anchor

See demo at regex101

With allowing leading zeros, you can reduce it to
^(?:[01]?\d\d?|2[0-4]\d|25[0-5])$

Community
  • 1
  • 1
bobble bubble
  • 11,968
  • 2
  • 22
  • 34
  • 1
    It isn't exactly what I wanted, as I wanted cases such as 000 or 001 or 02 to be accepted, but I modified it by prepending: `0\d|00\d|0\d\d|` – Abdul Feb 10 '16 at 04:03
0

As you are trying to only allow a range of numbers (0-255), why use regex at all? Instead, parse the string as an int and check if it falls within the range.

public static boolean isInRange(String input, int min, int max) {
    try {
        int val = Integer.parseInt(input);
        return val >= min && val < max;
    } catch (NumberFormatException e) {
        return false;
    }
}
FThompson
  • 27,043
  • 11
  • 53
  • 89
  • Unfortunately the purpose of the exercise is to use Regex only, even if there are much easier and better ways, otherwise it'd be cheating. – Abdul Feb 10 '16 at 02:13