仅正则表达式匹配,如果已找到分号

问题描述 投票:0回答:4

我想写一个匹配端口的正则表达式。这很好用,但通常时间也会匹配。我想创建否定的前瞻和后视,这样如果字符串中有另一个冒号,它就不应该匹配。但我犯了一个错误,我无法发现它:

基本上,我希望端口匹配,但时间不应该匹配。

(?<!:):\d{1,5}\b(?!:)

这里是保存的正则表达式的链接:https://regex101.com/r/GJIVKF/1

Edit1:有时,端口显示如下:443 和 :80,但没有 IP 信息。这就是为什么我正在研究环顾四周的解决方案。

regex regex-lookarounds
4个回答
0
投票

这个正则表达式:

¹

^\d+\.\d+\.\d+\.\d+:\K\d{1,5}

²

^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}:\K\d{1,5}

假设

ip's
只有

¹ 在线演示
² 在线演示


0
投票

如果你对一行中的单个

:
之后的任何事情感兴趣:

^[^:]*:(\d{1,5})$

并使用第 1 组作为您的端口。

如果你想更严格一点,将端口范围限制为实际的 0 到 65535,你可以使用这个:

^[^:]*:(6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[0-5]?\d{1,4})$

(为了“简洁起见;-)”我允许在此正则表达式中使用前导零)


0
投票

正如您提到的 Ecmascript,这里的解决方案可以独立匹配端口号或作为 IPv4 的结尾部分:

const regex = /(?:\.\d+|\B)(?::)(\d{1,5})\b(?!:)/g;

// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?:\\.\\d+|\\B)(?::)(\\d{1,5})\\b(?!:)', 'g')

const str = `10.0.243.7:38518    :440
62.11.21.68:443   port  :80
01:11:22
21:15:19
:443 `;
let m;

ports = Array.from(str.matchAll(regex), (m) => m[1])
console.log(ports)


0
投票

如果您使用的是 Javascript 并且可以使用可变长度后视,则可以在左侧断言

:
,但在左侧断言不是
.
,后跟数字,然后是
:

(?<=:)(?<!:\d+:)\d{1,5}\b(?!:)

正则表达式演示

const regex = /(?<=:)(?<!:\d+:)\d{1,5}\b(?!:)/g;
const s = `10.0.243.7:38518
62.11.21.68:443
01:11:22
21:15:19`;
console.log(s.match(regex));

如果你也想匹配冒号:

(?<!:\d+):\d{1,5}\b(?!:)

正则表达式演示

const regex = /(?<!:\d+):\d{1,5}\b(?!:)/g;
const s = `10.0.243.7:38518
62.11.21.68:443
01:11:22
21:15:19`;
console.log(s.match(regex));

© www.soinside.com 2019 - 2024. All rights reserved.