RegEx用于匹配特定格式的IP

时间:2019-05-15 18:52:15

标签: javascript regex regex-lookarounds

我有这行:

OUT = br0 SRC = 222.187.221.84 DST = 192.168.1.20 LEN = 60 OUT = br0 SRC = 222.187.221.84 DST = 192.168.1.20 LEN = 60 OUT = br0 SRC = 222.187.221.84 DST = 192.168.1.20 LEN = 60

我如何只获取src =(ipaddress)而仅获取ipaddress?

尝试:

SRC=(.+)(\d+)(.+?(?=DST))

4 个答案:

答案 0 :(得分:1)

您可以在正则表达式后面使用正向外观,如下所示:

(?<=SRC = )\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}

regex101示例:https://regex101.com/r/cuAUm3/1/

javascript代码:

const regex = /(?<=SRC = )\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/gm;
const str = `OUT = br0 SRC = 222.187.221.84 DST = 192.168.1.20 LEN = 60 OUT = br0 SRC = 222.187.221.84 DST = 192.168.1.20 LEN = 60 OUT = br0 SRC = 222.187.221.84 DST = 192.168.1.20 LEN = 60`;

console.log(str.match(regex));

结果:

Array(3)
0: "222.187.221.84"
1: "222.187.221.84"
2: "222.187.221.84"

答案 1 :(得分:1)

您可以使用此正则表达式从组1中提取IP。

SRC\s*=\s*(\d{1,3}(?:\.\d{1,3}){3})

请注意,此正则表达式还通过在正则表达式中使用SRC来放宽=\s*和IP之间的空白,并且启用不区分大小写的匹配将有助于匹配src

Regex Demo

JS代码演示

const s = 'OUT = br0 SRC = 222.187.221.84 DST = 192.168.1.20 LEN = 60 OUT = br0 SRC = 222.187.221.85 DST = 192.168.1.20 LEN = 60 OUT = br0 SRC = 222.187.221.86 DST = 192.168.1.20 LEN = 60'
const reg = /SRC\s*=\s*(\d{1,3}(?:\.\d{1,3}){3})/ig

while((m = reg.exec(s))) {
    console.log(m[1])
}

答案 2 :(得分:0)

这应该为您提供IP

var ipReg = /SRC = (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/;

var str = 'br0 SRC = 222.187.221.84 DST = 192.168.1.20 LEN = 60 OUT = br0 SRC = 222.187.221.84 DST = 192.168.1.20 LEN = 60 OUT = br0 SRC = 222.187.221.84 DST = 192.168.1.20 LEN = 60';

var ip = str.match(ipReg)[1];

console.log(ip)

答案 3 :(得分:0)

正如其他答案所建议的那样:您可以使用类似以下的内容:

var regex= /SRC = (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/g;

OR:

var regex= /SRC\s*=\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/g;

在括号中捕获您要匹配的组:

(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})

然后,您可以继续对字符串中的所有匹配项执行正则表达式。

var txt= "OUT = br0 SRC = 222.187.221.84 DST = 192.168.1.20 LEN = 60 OUT = br0 SRC = 222.187.221.84 DST = 192.168.1.20 LEN = 60 OUT = br0 SRC = 222.187.221.84 DST = 192.168.1.20 LEN = 60";
var regex= /SRC\s*=\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/g;

var match = regex.exec(txt);
while (match != null) {
    console.log(match[1]);
    match = regex.exec(txt);
}