Regex确定是否IPv6或IPv4以及是否给出端口-在www.regexr.com中工作,但不在我的JavaScript文件中[重复]

zsbz8rwp  于 2023-10-22  发布在  Java
关注(0)|答案(1)|浏览(81)

此问题已在此处有答案

Regular Expressions: difference between ^ and \A(4个答案)
上个月关门了。

var regexForAddress = /^(?:[0-9.]+|(?:\[[0-9a-fA-F:]+\]))$/;
var address = String('[2a00:1397:4:2a02::a1]:50434').match(regexForAddress);
console.log("Reached user customer data for user PublicIp address is " + address);

好的,我有IPV6,如下所示:[2a00:1397:4:2a02::a1]:50434和127.0.0.1:50434。希望获取不带IPV6和IPV4端口的IP地址。谢谢.显示空在JS的console.log的地址,但在regexr.com工作.请在这方面帮助我。

vltsax25

vltsax251#

去掉$,因为当地址后面跟着:port时,它将不匹配。

var regexForAddress = /^(?:[0-9.]+|\[[0-9a-fA-F:]+\])/;
console.log('127.0.0.1:50434'.match(regexForAddress));
console.log('[2a00:1397:4:2a02::a1]:50434'.match(regexForAddress));

如果您只想在地址后有端口时进行匹配,请使用lookahead来请求端口,但不将其包含在匹配中。你可以把$放在lookahead中。

var regexForAddress = /^(?:[0-9.]+|\[[0-9a-fA-F:]+\])(?=:\d+$)/;
console.log('127.0.0.1:50434'.match(regexForAddress));
console.log('[2a00:1397:4:2a02::a1]:50434'.match(regexForAddress));

相关问题