标签:
A报文
<?xml version="1.0" encoding="utf-8"?> <PACKET> <HEAD> <SERVICE_NAME>seeYou</SERVICE_NAME> </HEAD> <BODY> <CONTENT> <![CDATA[ <?xml version="1.0" encoding="utf-8"?> <PACKET> <![CDATA[ nice to meet you! ]]> </PACKET> ]]> </CONTENT> </BODY> </PACKET>
嵌套在A报文中的B报文
<?xml version="1.0" encoding="utf-8"?> <PACKET> <![CDATA[ nice to meet you! ]]> </PACKET>
场景
我得到A报文,后需要解析提取B报文转发给目标系统.
而现有解析代码如下:
package kingtool; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PatternTool { /** * 从regex表达式中提供对应的值 * @author King */ public static String parsePattern(String regex, String content ,int groupNum) { String ret = ""; String str = ""; String output =""; try { Pattern p = Pattern.compile(regex); Matcher m = p.matcher(content); if (m.find()) { for(int i = 0 ; i <= m.groupCount() ; i ++){ if(i == 0){ }else{ str = m.group(i); output = String.format("解析得正则表达式%s中group(%d)匹配的值\n",regex,i); System.out.println(output); System.out.println(str); } } ret = m.group(groupNum); System.out.println("返回第"+groupNum+"组匹配到的内容:\n"+ret); }else{ System.out.println("未解析到正则表达式"+regex+"匹配的的值\n"); } } catch (Exception e) { e.printStackTrace(); } return ret; } public static void main(String[] args) { String content = FileTool.readStringFromFile("D://c.txt", "GBK" ); String regex = "<CONTENT>(.*)(<!\\[CDATA\\[(.*)\\]\\]>)(.*)</CONTENT>"; String ret = parsePattern(regex,content,3); } }
解析后,打印结果如下(并非最终想要的B报文):
文件 D://c.txt存在与否?: true 读到的文件内容如下: <?xml version="1.0" encoding="utf-8"?><PACKET> <HEAD> <SERVICE_NAME>seeYou</SERVICE_NAME> </HEAD> <BODY> <CONTENT> <![CDATA[ <?xml version="1.0" encoding="utf-8"?> <PACKET> <![CDATA[ nice to meet you! ]]> </PACKET> ]]> </CONTENT> </BODY></PACKET> 解析得正则表达式<CONTENT>(.*)(<!\[CDATA\[(.*)\]\]>)(.*)</CONTENT>中group(1)匹配的值 <![CDATA[ <?xml version="1.0" encoding="utf-8"?> <PACKET> 解析得正则表达式<CONTENT>(.*)(<!\[CDATA\[(.*)\]\]>)(.*)</CONTENT>中group(2)匹配的值 <![CDATA[ nice to meet you! ]]> </PACKET> ]]> 解析得正则表达式<CONTENT>(.*)(<!\[CDATA\[(.*)\]\]>)(.*)</CONTENT>中group(3)匹配的值 nice to meet you! ]]> </PACKET> 解析得正则表达式<CONTENT>(.*)(<!\[CDATA\[(.*)\]\]>)(.*)</CONTENT>中group(4)匹配的值 返回第3组匹配到的内容: nice to meet you! ]]> </PACKET>
现在来分析以上原因:
标签:
原文地址:http://www.cnblogs.com/whatlonelytear/p/5764298.html