正则表达式以匹配多个以空格分隔的子网

时间:2018-10-16 18:00:51

标签: javascript regex angular

当前正则表达式以匹配由space rexp = /^([01]?\d\d?|2[0-4]\d|25[0-5])(?:\.[01]?\d\d?|2[0-4]\d|25[0-5]){3}(?:\/[0-2]\d|\/3[0-2])?$(\s(^([01]?\d\d?|2[0-4]\d|25[0-5])(?:\.[01]?\d\d?|2[0-4]\d|25[0-5]){3}(?:\/[0-2]\d|\/3[0-2])?$))*$/)分隔的多个子网

测试字符串192.168.2.1/24 192.168.2.1/32

2 个答案:

答案 0 :(得分:1)

您的正则表达式似乎已损坏。您可以尝试以下一种方法:

^([01]?\d\d?|2[0-4]\d|25[0-5])(?:\.[01]?\d\d?|2[0-4]\d|25[0-5]){3}(?:\/[0-2]\d|\/3[0-2])?(\s+([01]?\d\d?|2[0-4]\d|25[0-5])(?:\.[01]?\d\d?|2[0-4]\d|25[0-5]){3}(?:\/[0-2]\d|\/3[0-2]))*$

另一个选择是使用Java脚本解析字符串,并为每段使用更简单的正则表达式。这是一个示例:

const s = '192.168.2.1/24 192.168.2.1/32 250.161.23.1/32 0.1.2.1/01';
const pattern = /([01]?\d\d?|2[0-4]\d|25[0-5])(?:\.[01]?\d\d?|2[0-4]\d|25[0-5]){3}(?:\/[0-2]\d|\/3[0-2])/;
const result = s.trim().split(/\s+/).map(e => e.match(pattern) != null).reduce((result, next) => result && next, true);
console.log(result);

此打印:

true

答案 1 :(得分:0)

尽管您当然可以使用regex分解字符串,但使用这样的代码可能会容易得多:

subnetsString = "192.168.2.1/24 192.168.2.1/32";
subnets = subnetsString.split(" ");
firstSubnet = subnets[0];
ip = firstSubnet.split("/")[0];

console.log(ip);  // output: 192.168.2.1