Tuesday, September 4, 2012

Get list of strings between two strings

public static List<String> getStringInBetween(String strBegin, String strEnd, String strSource){

    List<String> list = new ArrayList<String>();
   int iEnd = 0;
   int iIndexOfBegin = strSource.indexOf(strBegin);
  
   while(iIndexOfBegin != -1 ){
       strSource = strSource.substring(iIndexOfBegin  + strBegin.length());
       iEnd = strSource.indexOf(strEnd);
       list.add(strSource.substring(0, iEnd));
       iIndexOfBegin = strSource.indexOf(strBegin);
   }
  
   return list;
}


Use:

List<String> tokens =getStringInBetween("[\"","\"]", "Input: {attr[\"role\"] == 'admin' ? attr[\"admintitle\"] :  attr[\"supertitle\"]}");
for(String token: tokens){
   System.out.println(token);
}


Output:
role
admintitle
supertitle