比如:aa bb [cc dd ee] ff
分割成
aa
bb
[cc dd ee]
ff
不存在嵌套[],例如:aa [bb [cc dd]] ee
不存在类似左右不匹配,例如:aa bb [cc dd ee和aa bb cc] dd ee
就这样。。。
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Test {
public static void main(String[] args) throws Exception {
String[] split = split("aa bb [cc dd ee] [ff gg] ee", " ");
for(String s : split)
System.out.println(s);
}
private static String[] split(String str, String regex) throws Exception {
List<String> resultList = new ArrayList<>();
if(str == null || str.isEmpty()) return resultList.toArray(new String[0]);
String[] split = str.split(regex);
Queue<String> queue = new LinkedList<>();
for(String s: split){
if(s.charAt(0) == '[' && s.charAt(s.length() - 1) == ']'){
resultList.add(s);
continue;
}
if(s.charAt(0) == '['){
queue.offer(s);
continue;
}
if(s.charAt(s.length() - 1) == ']'){
if(queue.isEmpty())
throw new Exception("格式不对");
StringBuilder sb = new StringBuilder();
while(!queue.isEmpty()){
sb.append(queue.poll());
sb.append(" ");
}
sb.append(s);
resultList.add(sb.toString());
continue;
}
if(!queue.isEmpty()) queue.offer(s);
else resultList.add(s);
}
return resultList.toArray(new String[0]);
}
}
public static void main(String[] args) throws Exception {
String str = "[aa gg ww [ff gg hh]] aa bb [cc dd ee] ff";
int k = 0;
StringBuffer sb = new StringBuffer();
List<String> result = new ArrayList<>();
for(int i=0;i<str.length();i++){
char c = str.charAt(i);
if(c == '[' || c == ']')
k++;
if(c == ' ' && k != 1 ){
if(sb.length() != 0)
result.add(sb.toString());
sb = new StringBuffer();
if(k == 2)k=0;
continue;
}
sb.append(c);
}
if(sb.length() != 0){
result.add(sb.toString());
}
System.out.println(result);
}
楼上专业啊,看到问题解决问题
public class TestDemo {
public static void main(String[] args) {
String str = "aa bb [cc dd ee] ff";
String a[] = str.split(" ");
String b[] = new String[4];
b[0] = a[0];
b[1] = a[1];
b[2] = a[2] + " " + a[3] + " " + a[4];
b[3] = a[5];
for(String s : b) {
System.out.println(s);
}
}
}