package builder; import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) { //下面期望输出[jgajgaagi;aghuhagajagg;;g, ga23ty1] String str="agaggaga<a;agpjgajgaagi;aghuhagajagg;;gakagkogagpga23ty1ak1hg"; String open="a*gp"; String close="ak"; //下面期望输出[ag, pj, i;aghuha, g;;, ko] String str2="agaggaga<a;agpjgajgaagi;aghuhagajagg;;gakagkogaga23ty11hg"; String open2="ag"; String close2="ga"; String str3="agaggaga<a;agpjgajgaagi;aghuhagajagg;;gaaxkagkogagpga23ty1ak1hgagagaagggaagp124321112a11k"; String open3="gp"; String close3="a*k"; List<String> midList = getMidList(str, open, close); List<String> midList2 = getMidList(str3, open3, close3); System.out.println(midList); System.out.println(midList2); } public static List<String> getMidList(String str,String open,String close){ List<String> retList = new ArrayList<>();//存储结果 if(isEmpyty(str)|| isEmpyty(open) || isEmpyty(close)){ return retList; } List<String> openList = getString(str, open); if(!openList.isEmpty()) { str = getMidTemp(openList, str, retList, close); while (true) { if (null == str) { return retList; } openList = getString(str, open); if (openList.isEmpty()) { return retList; } str = getMidTemp(openList, str, retList, close); } } return retList; } public static String getMidTemp(List<String> openList,String str,List<String> retList,String close){ String temp=null; outer: for (String pre : openList) { int i = str.indexOf(pre); if(i==-1){ continue outer; } i=i+pre.length(); str=str.substring(i);//去掉头 List<String> closeList = getString(str, close); for (String sub : closeList) { int dd = str.indexOf(sub); if(dd==-1){ continue; } temp=str; retList.add(str.substring(0, dd)); temp=temp.substring(dd+sub.length()); return temp; } } return temp; } public static boolean isEmpyty(String str){ if(null==str || str=="" || str.trim().length()==0){ return true; } return false; } public static List<String> getString(String str,String open) { String[] split = open.split("\*"); List<String > list=new ArrayList<>(); if(split.length==1){ String pre=split[0]; if(str.indexOf(pre)!=-1){ list.add(pre); } return list; } if(split.length>=3){ return list; } String s1 = split[0]; String s2 = split[1]; String temp=null; while (true){ int i = str.indexOf(s1); if(i==-1){ break; } int i2 = str.indexOf(s2); if(i2==-1){ break; } if(i<i2){ temp=str; list.add(str.substring(i,i2+s2.length())); str=temp.substring(i2+s2.length()); }else { break; } } return list; } }