gpt4 book ai didi

java - 在java中为行之间存在的字符串编写正则表达式

转载 作者:太空宇宙 更新时间:2023-11-04 06:58:59 25 4
gpt4 key购买 nike

我的输入字符串是:

subtype=forward,level=notice,vd=root,srcip=10.100.1.121,srcport=55844,srcintf=port1,dstip=173.193.156.43,dstport=80,dstintf=port16,sessionid=1224203695,status=close
subtype=forward,level=notice,vd=root,srcip=10.100.1.121,srcport=55844,srcintf=port1,dstip=173.193.156.43,dstport=80,dstintf=port16,sessionid=1224203695,status=open

这是我尝试过的代码:

Pattern patt = Pattern.compile("(srcip=(?:\\d+\\.)+\\d+)(?:.*)?(dstip=(?:\\d+\\.)+\\d+)(?:.*)?(status=(?=.*close.*)(?:.*)?(dstport=(\\d+))");

BufferedReader r = new BufferedReader(new FileReader("ttext.txt"));

// For each line of input, try matching in it.
String line;
while ((line = r.readLine()) != null) {
// For each match in the line, extract and print it.
Matcher m = patt.matcher(line);
while (m.find()) {
// Simplest method:

System.out.print(" " + m.group(1) + " " );
System.out.print(" " + m.group(2) + " " );
System.out.print(" " + m.group(3) + " " );
System.out.println(" " + m.group(4));

预期输出是:

srcip=10.100.1.121 dstip=173.193.156.43 srcport=55844 status=close dstport=80  

但这是我得到的输出:

srcip=10.100.1.121  dstip=173.193.156.43  dstip=173.193.156.43  dstport=80
srcip=10.100.1.121 dstip=173.193.156.43 dstip=173.193.156.43 dstport=80

有什么建议吗?

最佳答案

捕获组的顺序与输入中字段的顺序不对应。这是正则表达式的重新排序版本,它捕获您需要的 5 个组:

String s = "subtype=forward,level=notice,vd=root,srcip=10.100.1.121,srcport=55844,srcintf=port1,dstip=173.193.156.43,dstport=80,dstintf=port16,sessionid=1224203695,status=close";

Pattern p = Pattern.compile("(srcip=(?:\\d+\\.)+\\d+)(?:.*)?(srcport=(?:\\d+))(?:.*)?(dstip=(?:\\d+\\.)+\\d+)(?:.*)?(dstport=(?:\\d+))(?:.*)?(status=(?:.*))");
Matcher m = p.matcher(s);

if (m.find()) {
System.out.println(m.group(1) + " " + m.group(3) + " " + m.group(2) + " " + m.group(5) + " " + m.group(4));
}

请注意,我还修复了一个未封闭的组,并使其中一个组不捕获。

关于java - 在java中为行之间存在的字符串编写正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22361490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com