java截取字符串
我想要截取一段字符串多次出现的内容。就比如String str="adfaa21aabb/dfccdsfdsds23ccdd/oiuodfg2ggee/";想要截取df到/之间的内容,怎么重复的截取多次。
------解决方案--------------------public static void main(String arg[]) throws Exception {
String s = "String str=\"adfaa21aabb/dfccdsfdsds23ccdd/oiuodfg2ggee/";
Pattern p = Pattern.compile("df(.*?)/", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group(1));
}
}
------解决方案--------------------/*
* 根据开头的字符结尾的字符以及之间的字符返回匹配的字符串
* str 待匹配的字符串,begin开始匹配的字符串,key匹配的中间字符,end匹配的结束字符
*/
public static String[] match(String str, String begin,String key,String end)
{
String [] strMc = new String[9];
int beginIndex = str.indexOf(begin);
int endLength = end.length();
int endIndex = str.indexOf(end,beginIndex+begin.length())+endLength;
int i = 0;
while(-1!=beginIndex&&-1!=endIndex)
{
String sub = str.substring(beginIndex, endIndex);
if(-1!=sub.indexOf(key))
{
strMc[i] = new String(str.substring(beginIndex, endIndex+endLength));
i++;
}
beginIndex = str.indexOf(begin, endIndex);
endIndex = str.indexOf(end, beginIndex);
}
return strMc;
}
可以match("df","","/");
------解决方案--------------------String str = "adfaa21aabb/dfccdsfdsds23ccdd/oiuodfg2ggee/";
String[] strs=str.split("/");
for (String s : strs) {
if(s.indexOf("df")!=-1){
System.out.println(s.substring(s.indexOf("df")+2,s.length()));
}
}