gpt4 book ai didi

java - 用匹配器解析协议(protocol)段落?

转载 作者:行者123 更新时间:2023-12-01 14:22:54 29 4
gpt4 key购买 nike

我尝试编写一个服务器-客户端程序。我可以发送协议(protocol)文本并正确获取文本。但是当我尝试解析文本时,我遇到了 Matcher 类的问题。因为它只匹配第一行。那么我怎样才能找到正确的字符串并解析文本。我认为 Matcher 不会尝试匹配其他行。如果它是错误,我该如何修复它,或者我将拆分每一行,然后尝试解析。

下面是一个示例,我无法匹配表达式上的字符串。

String veri ="SIP/2.0 200 OK\r\n"
+"Via: SIP/2.0/UDP 10.10.10.34:5060;branch=z9hG4bK3834f681a;received=10.10.10.17\r\n"
+"From: <sip:4420145@10.10.10.24>;tag=as153459088\r\n"
+"To: <sip:44520145@10.10.10.24>;tag=as6163450a5a\r\n"
+"Call-ID: 1e0ssdfdb7f456e5977bc0df60645348cf1ce@[::1]\r\n"
+"CSeq: 18368 REGISTER\r\n"
+"Server: Asterisk PBX 11.3.0\r\n"
+"Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO, PUBLISH\r\n"
+"Supported: replaces, timer\r\n"
+"Expires: 120\r\n"
+"Contact: <sip:345dgd@10.10.10.17:5060>;expires=120\r\n"
+"Date: Sat, 29 Jun 2013 14:00:50 GMT\r\n"
+"Content-Length: 0";
//veri="To: <sip:3453@10.10.10.24>;tag=34dgd\r\n";
Pattern p1 = Pattern.compile("^To\\: (.*);tag=(.*)$");

Matcher m = p1.matcher(veri);

if(m.find()){

System.out.println(m.group(1).trim());
}

最佳答案

您只需使用 (?m) 嵌入标志或 Pattern.MULTILINE 启用匹配的多行模式正则表达式中的模式。这样,$ 将停在每个行终止符处,而不是整个输入的末尾。

Pattern p1 = Pattern.compile("(?m)^To: (.*);tag=(.*)$");

另外,代替:

if(m.find())

你应该使用:

while (m.find())

另请注意,您的匹配器引用名称不匹配。您在 if 中使用 matcher,但定义了 m

P.S:您将在末尾为字符串重新分配一个新值。确保使用 += 而不是 =

关于java - 用匹配器解析协议(protocol)段落?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17390965/

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