简体   繁体   English

基于条件的字符串的子串

[英]Substring of a string based on condition

I have a string like below (read from a file and stored in a String) 我有一个像下面的字符串(从文件中读取并存储在字符串中)

<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>

Requirement: 需求:

If string values matches to 'event_code="CP"' then I need to return complete data in between <textmessage> ---- </textmessage> as shown below. 如果字符串值与'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>

A combination of those might help 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 这些的组合可能有助于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

Search for 'event_code="CP" with find() or match() if is there... 用find()或match()搜索'event_code =“CP”,如果有...

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

Other option is to use xml parses, but regex are really simple for what you want. 其他选项是使用xml解析,但正则表达式对于你想要的东西来说非常简单。

if the pattern is really constant, yo can even use indexOf to go faster on your searches... http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String) 如果模式真的是常量,你甚至可以使用indexOf来加快搜索... http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java .lang.String)

if they are on the same location, then just reading from there is enough.. 如果他们在同一个地方,那么只需从那里读取就足够了..

Why don't you try to parse that String as a XML using DOM? 为什么不尝试使用DOM将该String解析为XML? With this you just have to compare the value of each "text" node and if it's value matches you return the whole parent node, as String for example... 有了这个你只需要比较每个“文本”节点的值,如果它的值匹配,你返回整个父节点,例如String ...

Here is a basic sample of how it DOM works in Java: http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/ 以下是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