类似于:jdbc:mysql://localhost:3306/bill?characterEncoding=utf-8这种格式字符串,想分别将mysql 、 localhost、3306、bill信息从该字符串中提取出来,用该如何提取。
希望大家给点建议和思路
本问题已解决:
本人思路有两种,第一种思路
//第一种方法
/**
*
* @param tags 所要处理的字符
* @param str 所要处理的字符串
* @return
* @throws Exception
*/
public static List<String> getStrsByTags(String[] tags, String str)
throws Exception {
int[] index = new int[tags.length];
List<String> result = new ArrayList<String>();
int flag = 0;
int cutPoint = 0; // 截取点
String block = "";
while (flag == 0) {
System.out.println("循环开始了,flag = " + flag);
for (int i = 0; i < tags.length; i++) {
index[i] = str.indexOf(tags[i]);
}
Arrays.sort(index); // 数组进行排序
if (index[(tags.length) - 1] < 0) { // 数组中最大的一项小于零
// 终止while循环
flag = 1;
}
for (int j = 0; j < index.length; j++) {
if (index[j] >= 0) {
cutPoint = index[j] + 1;
break;
}
}
System.out.println("字符串中最先出现的位置为" + cutPoint + " 最后出现的位置为"
+ index[(tags.length) - 1]);
block = str.substring(0, cutPoint);
str = str.substring(cutPoint);
result.add(block); // 将字符串添加到list中
}
return result;
}
//第二种方法
/**
*
* @param tags 字符串中有的标志
* @param str 要处理的字符串
* @param my 将所有的标志都转换为的标志
* @return
* @throws Exception
*/
public static List<String> getByTags(String[] tags,String str,String my)throws Exception{
List<String> result = new ArrayList<String>();
for(String tag :tags){
str = str.replaceAll(tag, my);
}
String[] strs = str.split(my);
for(String s :strs){ //剔除为空的数据
if(s!=null && s!="" && !s.isEmpty()){
result.add(s);
}
}
return result;
}
//测试
public static void main(String[] args){
String[] strs= {"/",":","[?]"};
String str = "jdbc:mysql://localhost:3306/bill?characterEncoding=utf-8";
try{
List<String> list = getByTags(strs, str,",");
for(String result : list){
System.out.println(">>>>>"+result);
}
}catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
方法一 该种方法还没有真正的获取所需要的字符串,需要对获取的字符串再进行一些筛选,比如便利这些数据,将原有的那些字符替换为“” ,这个思路就是不断的去截取这个字符串,一直截取到不能再截取为止,并将截取下来的字符串保存下来
方法二是将所有特殊字符全部替换为想要的字符,通过字符获取数组,并过滤掉数组中的杂质
原文:http://my.oschina.net/pumpkin0523/blog/416716