繁体   English   中英

基于条件的字符串的子串

[英]Substring of a string based on condition

我有一个像下面的字符串(从文件中读取并存储在字符串中)

<textmessages>
<textMessage timestamp="1424708212905">
<property name="tcs_car_kind" value="M32"/>
<property name="prev_cmdy_abrv" value="AUTOS"/>
<text><![CDATA[event_code="AP"]]></text>
</textMessage>
<textMessage timestamp="1424708212902">
<property name="shp_prim" value=""/>
<property name="prev_cmdy_abrv" value="AUTOS"/>
<text><![CDATA[event_code="CP"]]></text>
</textMessage>
<textMessage timestamp="1424708212902">
<property name="co_part_frm_nbr" value=""/>
<property name="prev_cmdy_abrv" value="AUTOS"/>
<text><![CDATA[event_code="LP"]]></text>
</textMessage>
</textmessages>

需求:

如果字符串值与'event_code =“CP”'匹配,那么我需要在<textmessage> ---- </textmessage>之间返回完整数据,如下所示。

<textMessage timestamp="1424708212902">
<property name="co_part_frm_nbr" value=""/>
<property name="shp_prim" value=""/>
<property name="prev_cmdy_abrv" value="AUTOS"/>
<text><![CDATA[event_code="CP"]]></text>
</textMessage>

这些的组合可能有助于http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html http://docs.oracle.com/javase/7/docs/api /java/util/regex/Matcher.html

用find()或match()搜索'event_code =“CP”,如果有...

Pattern p = Pattern.compile("pattern here"); if(p.matcher(content).find()){...}

其他选项是使用xml解析,但正则表达式对于你想要的东西来说非常简单。

如果模式真的是常量,你甚至可以使用indexOf来加快搜索... http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java .lang.String)

如果他们在同一个地方,那么只需从那里读取就足够了..

为什么不尝试使用DOM将该String解析为XML? 有了这个你只需要比较每个“文本”节点的值,如果它的值匹配,你返回整个父节点,例如String ...

以下是DOM如何在Java中工作的基本示例: http//www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM