2

I try to create a regex which matchs with IPv4.

I have this code

//numbers from 10 to 99
String r10to99 = "[1-9][0-9]";

//numbers from 100 to 199
String r100to199 = "1[0-9][0-9]"; 

//numbers from 200 to 255
String r200to255 = "2[0-4][0-9]|25[0-5]"; 

//combine all - numbers from 0 to 255   
String r0to255 = "[0-9]|" + r10to99 + "|" + r100to199 + "|" + r200to255; 

String regexIP = r0to255 + "[.]" + r0to255 + "[.]" + r0to255 + "[.]" + r0to255; 

System.out.println("15.15.15.15".matches(regexIP)); //->false - should be true
System.out.println("15".matches(regexIP)); //->true - should be false

My problem is at regexIP. It match only with numbers from 0 to 255. Like r0to255.

How to concat multiple r0to255 with .(dot) between them?

r0to255.r0to255.r0to255.r0to255

KunLun
  • 3,109
  • 3
  • 18
  • 65

2 Answers2

2

You need to group these patterns, see the fixed code:

String r10to99 = "[1-9][0-9]"; //numbers from 10 to 99
String r100to199 = "1[0-9][0-9]"; //numbers from 100 to 199
String r200to255 = "2[0-4][0-9]|25[0-5]"; //numbers from 200 to 255

//combine all - numbers from 0 to 255   
String r0to255 = "(?:[0-9]|" + r10to99 + "|" + r100to199 + "|" + r200to255 + ")"; 

String regexIP = r0to255 + "(?:[.]" + r0to255 + "){3}"; 

System.out.println("15.15.15.15".matches(regexIP)); // true
System.out.println("15".matches(regexIP)); // false

See Java demo online

Here, "(?:[0-9]|" + r10to99 + "|" + r100to199 + "|" + r200to255 + ")" groups the r10to99, r100to199 and r200to255 so as inside a larger pattern (using a non-capturing group), the | would not ruin the whole pattern.

The r0to255 + "(?:[.]" + r0to255 + "){3}" pattern is actually a r0to255 pattern that is followed with three sequences of . and r0to255 pattern.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Using `?:` at `r0to255` mean to resolve all, without changing my regexIP. It is necesary to use `?:` at `regexIP`? – KunLun Sep 26 '18 at 16:10
  • 1
    @raul1ro You are right, but `ababab` pattern is too verbose, the `(?:ab){3}` notation is easier and more maintainable. Well, it is up to you. – Wiktor Stribiżew Sep 26 '18 at 18:53
-1

For the sake of completeness, of course Apache already has a solution for this.

SDekov
  • 9,276
  • 1
  • 20
  • 50
  • I know that, but why is wrong to try to implement my own method? By trying to find a regex for that I learned new things. – KunLun Sep 26 '18 at 16:59