Concat多个正则表达式

时间:2018-09-26 15:51:44

标签: java regex

我尝试创建一个与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

2 个答案:

答案 0 :(得分:2)

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

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)中将{{1} }不会破坏整个模式。

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

答案 1 :(得分:-1)

出于完整性考虑,Apache当然已经为此提供了解决方案。