-6

In my project we have a regular expression for IPV 4, below is the format for it.

I am not able to understand how it fits the IP.

private static final Pattern PATTERN = Pattern.compile(
        "^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");

I tried to understand using online tool - https://regex101.com/, but not able to get clarity how it works.

The same solution is given in this SO also - Validate IPv4 address in Java

learner
  • 4,858
  • 9
  • 47
  • 92
  • You don't understand probably because it doesn't work: https://ideone.com/WjUCF5 – ifly6 Sep 06 '18 at 21:45
  • It is working solution, also mentioned in this SO - https://stackoverflow.com/questions/5667371/validate-ipv4-address-in-java – learner Sep 06 '18 at 21:47
  • @ifly6 `System.out.println("192.168.0.10".matches("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"));` returns `true` for me... – Matt Clark Sep 06 '18 at 21:47
  • 2
    @ifly6 That regular expression in your link is not the same as the one in the question. – khelwood Sep 06 '18 at 21:49
  • Take a look at diagram at: https://regexper.com/#%28%5B01%5D%3F%5Cd%5Cd%3F%7C2%5B0-4%5D%5Cd%7C25%5B0-5%5D%29. It should help you understand `([01]?\d\d?|2[0-4]\d|25[0-5])` part (it is X at X.X.X.X which can be represented as `(X.){3}X`) – Pshemo Sep 06 '18 at 22:46
  • Just remember value like `1` in OP can be written as `01` and `001` so you need to accept it. This means you can accept all single and double digit numbers. Only problem is with 3 digit numbers because you can't accept 256 and bigger values. So if 3 digit number which start with 0 or 1 (`0xx` and `1xx` - where `x` is any digit) are OK because they are always smaller than 256. This gives us `[01]\d\d`. Also numbers in form `20x` `21x` `22x` `23x` `24x` (`2[0-4]\d`) are safely acceptable. Finally you also need to accept `250 - 255` (`25[0-5]`). – Pshemo Sep 06 '18 at 22:55
  • Rest of it is shortening of regex, like `\d|\d\d` can be written as as single `\d\d?` which will handle single and double digits. We can combine it with ``[01]\d\d\`` and get ``[01]?\d\d?`` which will accept numbers in range `0-9, 00-99, 000-199`. – Pshemo Sep 06 '18 at 22:59

1 Answers1

0

match 0 or 1 optional then two digits (0-9) eg 0, 122, 99
or 2 then one digit 0-4 then one digit (0-9) eg 204, 222
or 25 then one digit 0-5 eg 250, 255
then a Dot (.)
repeat 3 times
then the same thing but once and without the Dot at the end.

be aware that the \'s should be changed to \ when you put it in a tool like that

mavriksc
  • 1,086
  • 1
  • 7
  • 10