我想从输入字符串中过滤掉srcport和dstport。这是我试过的代码:
String input = "2014<>10.100.2.3<><189>date=2014-01-16,time=11:26:14,devname=B3909601569,devid=B3909601569,logid=000013,type=traffic,srcip=192.168.192.123,srcport=2072,srcintf=port2,dstip=10.180.1.105,dstport=3206,dstintf=port1,sessionid=121543,status=close,policyid=196,service=MYSQL,proto=6,duration=10,sentbyte=3910,rcvdbyte=175085,sentpkt=74,rcvdpkt=132";
Pattern p = Pattern.compile("(srcport=)(\\d+).[\\s]?(dstport=)(\\d+)");
Matcher m = p.matcher(input);
StringBuffer result=new StringBuffer();
while (m.find()) {
System.out.println("Srcport: " + m.group(2) + " & ");
System.out.println("Dstport: " + m.group(4));
}
System.out.println(result);
但它没有显示任何输出。正则表达式中是否存在错误
Pattern p = Pattern.compile("(srcport=)(\\d+).[\\s]?(dstport=)(\\d+)");
或println行
System.out.println("Srcport: " + m.group(2) + " & ");
System.out.println("Dstport: " + m.group(4));"
任何建议都将受到高度赞赏。
答案 0 :(得分:1)
请参阅以下对正则表达式和捕获的组的更改:
String input = "2014<>10.100.2.3<><189>date=2014-01-16,time=11:26:14,devname=B3909601569,devid=B3909601569,logid=000013,type=traffic,srcip=192.168.192.123,srcport=2072,srcintf=port2,dstip=10.180.1.105,dstport=3206,dstintf=port1,sessionid=121543,status=close,policyid=196,service=MYSQL,proto=6,duration=10,sentbyte=3910,rcvdbyte=175085,sentpkt=74,rcvdpkt=132";
Pattern p = Pattern.compile("srcport=(\\d+).*?dstport=(\\d+)"); // update regex
Matcher m = p.matcher(input);
StringBuffer result=new StringBuffer();
while (m.find()) {
System.out.println("Srcport: " + m.group(1)); //print groups 1 + 2
System.out.println("Dstport: " + m.group(2));
}
System.out.println(result);
答案 1 :(得分:0)
您忘记在正则表达式中使用或(|
)
srcport=(\\d+)|dstport=(\\d+)
您的代码将是
while (m.find())
{
if(m.group().startsWith("srcport"))
System.out.println("Srcport: " + m.group(1) + " & ");
else
System.out.println("Dstport: " + m.group(1));
}
答案 2 :(得分:0)
试试这个:
Pattern p = Pattern.compile("srcport=(\\d+)|dstport=(\\d+)");
答案 3 :(得分:0)
尝试以下代码。我在我的系统中运行它并且它工作正常。
String input =“2014&lt;&gt; 10.100.2.3&lt;&gt;&lt; 189&gt; date = 2014-01-16,time = 11:26:14,devname = B3909601569,devid = B3909601569,logid = 000013,类型=流量,srcip = 192.168.192.123,srcport = 2072,srcintf = PORT2,dstip = 10.180.1.105,dstport = 3206,目的接口= PORT1,的sessionid = 121543,状态=关闭,策略ID = 196,服务= MYSQL,原= 6,持续时间= 10,sentbyte = 3910,rcvdbyte = 175085,sentpkt = 74,rcvdpkt = 132" ;
Pattern p = Pattern.compile("(srcport=)(\\d+)((.*)?)(dstport=)(\\d+)(\\.)*");
Matcher m = p.matcher(input);
StringBuffer result=new StringBuffer();
while (m.find()) {
System.out.println(m.group());
System.out.println("Srcport: " + m.group(2) );
System.out.println("Dstport: " + m.group(6));
}