Extract string from string in JAVA

Sample Code:

If you want to extract exact query from String or Log file

testOut_Log: START RequestId: 13b73ed9-b101-11e8-8619-91946b18fd8a Version: $LATEST
2018-09-05 11:44:41 <13b73ed9-b101-11e8-8619-91946b18fd8a> INFO  UpcDaoImpl:QUERY : SELECT apn, epc, rpc_fmt_cd FROM tbl_data WHERE apn= '43781661' OR apn= '63535011' OR apn= '19870' OR apn = '1023313'
2018-09-05 11:44:42 <13b73ed9-b101-11e8-8619-91946b18fd8a> INFO  addpcDaoImpl:RPT 

 

Required string :

SELECT apn, epc, rpc_fmt_cd FROM tbl_data WHERE apn= '43781661' OR apn= '63535011' OR apn= '19870' OR apn = '1023313'

Solution:

String myQuery = testOutput_Log.substring(testOutput_Log.indexOf("QUERY : "));
System.out.println("myQuery: \n"+ myQuery);
String myQuery2 = myQuery.substring(myQuery.indexOf("SELECT"), myQuery.indexOf("\n"));
System.out.println("myQuery3: \n"+ myQuery2);

out put:

SELECT apn, epc, rpc_fmt_cd FROM tbl_data WHERE apn= '43781661' OR apn= '63535011' OR apn= '19870' OR apn = '1023313'

Note:

Here I used to string variables to extract the query string because of Index out of bound exception

 

 

 

 

 

 

 

Leave a comment