简体   繁体   中英

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.

<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

Search for 'event_code="CP" with find() or match() if is there...

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.

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)

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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