经常会用到查找字符串操作,下面的函数可以一次截取到想要的字符串。
src:源串
keySet:用于界定结果的关键字集合,是一个字符串,每个关键字以\r\n间隔。
public static void main(String[] args) {
// TODO Auto-generated method stub
String s="<a href=\"/a/b/mylike?&pn=3\">下一页</a>";
System.out.println(lastFind(s,">下一页<\r\n\"\r\n\""));
}
public static String find(String src,String keySet){
String[] keys=keySet.split("\r\n");
String key="";
if(keys.length==1) return src;
for(int i=0;i<keys.length-1;i++){
key=keys[i];
src=src.substring(src.indexOf(key) + key.length());
}
src=src.substring(0,src.indexOf(keys[keys.length-1]));
return src;
}
public static String lastFind(String src, String keySet){
String[] keys=keySet.split("\r\n");
String key="";
if(keys.length==1) return src;
for(int i=0;i<keys.length-1;i++){
key=keys[i];
src=src.substring(0,src.lastIndexOf(key));
System.out.println(src);
}
src=src.substring(src.lastIndexOf(keys[keys.length-1]) +keys[keys.length-1].length());
return src;
}