我尝试创建一个与IPv4匹配的正则表达式。

我有这个代码

//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


我的问题在regexIP。它仅与0到255之间的数字匹配。例如r0to255

如何将多个r0to255与它们之间的.(dot)连接在一起?

r0to255.r0to255.r0to255.r0to255

最佳答案

您需要对这些模式进行分组,请参见固定代码:

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


Java demo online

在这里,"(?:[0-9]|" + r10to99 + "|" + r100to199 + "|" + r200to255 + ")"r10to99r100to199r200to255分组,以便在更大的模式(使用non-capturing group)中,|不会破坏整个模式。

r0to255 + "(?:[.]" + r0to255 + "){3}"模式实际上是一个r0to255模式,后跟三个序列的.r0to255模式。

10-07 23:54