鉴于这样的输入,56.1.2.3 56.1.2.4 255.255.255.254 56.1.2.7-9 56.5.1.1到56.5.1.7,我需要一个正则表达式,可以选出括号中的内容[56.1.2.3] [56.1.2.4 255.255.255.254] [56.1.2.7-9] [56.5.1.1至56.5.1.7]。
这就是我所拥有的:
private static final String IP_Address = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\d";//56.1.2.3
private static final String IP_WithMask = "(\\d{1,3}.){3}(\\d{1,3})(?:\\s+[255])(\\d{1,3}.){3}(\\d{1,3})"; //56.1.2.3 255.255.255.254
private static final String IP_CIDR = "(\\d{1,3}.){3}(\\d{1,3})(?:\\s*/)(\\d{1,3})"; //56.1.2.3/24
private static final String IP_ADDRESS_Dash_Numeric_RANGE = "((\\d{1,3}.){3}(\\d{1,3})(?:\\s*-)(\\d{1,3}))";// 56.1.2.3-4
private static final String IP_ADDRESS_Dash_ADDRESS_RANGE = "((\\d{1,3}.){3}(\\d{1,3})(?:\\s*-\\s*)(\\d{1,3}.){3}(\\d{1,3}))";//56.1.2.3-56.1.2.5
private static final String IP_ADDRESS_To_Numeric_RANGE = "(\\d{1,3}.){3}(\\d{1,3})(?:\\s*[T|t][O|o]\\s*)(\\d{1,3})";//56.1.2.3 to 255
private static final String IP_ADDRESS_To_ADDRESS_RANGE = "((\\d{1,3}.){3}(\\d{1,3})(?:\\s*[T|t][O|o]\\s*)(\\d{1,3}.){3}(\\d{1,3}))";//56.1.2.3 to 56.1.3.5`
问题是我的正则表达式无法找出单个IP与IP后跟掩码(56.1.2.3 255.x.x.x)之间的差异。其他类型也存在同样的问题。
答案 0 :(得分:0)
我测试了下面的正则表达式,适用于所有情况。
请参阅格式化正则表达式中的注释
解密结果的方法是测试组3-6的IP类型
捕获所有组件,甚至段开始。
正则表达式:
(\d{1,3}(?:\.\d{1,3}){2}\.(\d{1,3}))(?:(?:-|\s+to\s+)(\d{1,3}(?![\d\.]))|(?:-|\s*to\s+)(\d{1,3}(?:\.\d{1,3}){3})|\s+(25\d(?:\.\d{1,3}){3})|\s*/(\d{1,3}))?
格式化(with this app):
( # (1), IP
\d{1,3}
(?: \. \d{1,3} ){2}
\.
( \d{1,3} ) # (2), From segment
)
(?:
(?: - | \s+ to \s+ )
( # (3), Dash/To segment
\d{1,3}
(?! [\d\.] )
)
|
(?: - | \s* to \s+ )
( # (4), Dash/To range
\d{1,3}
(?: \. \d{1,3} ){3}
)
|
\s+
( # (5), Mask
25 \d
(?: \. \d{1,3} ){3}
)
|
\s* /
( # (6), Port
\d{1,3}
)
)?