如将String s = "{1,2,{3,4}}"分割为String[] ss = {"1","2","{3,4}"}; 的形式.
这里例子中数组只有两维,实际中可能为很多维.
用String.split(s)的话正则表达式怎么写?

解决方案 »

  1.   

    只用String.split(s)估计是不行的
      

  2.   

    写了个逐字解析的,谁给测测效率
    import java.util.Arrays;public class OneDimensionalityDecoder { public static void main(String args[]) {
    String input = "{1,2,{3,4,{5,6}},{7,8}}";
    int[] bounderies = getBounderies(input);
    System.out.println(Arrays.toString(bounderies));
    String[] result = split(input, bounderies);
    System.out.println(Arrays.toString(result));
    } public static String[] split(String input, int[] bounderies) {
    String[] result = new String[bounderies.length - 1];
    if (bounderies.length == 0) {
    result[0] = input;
    return result;
    }
    for (int i = 0; i < bounderies.length - 1; i++) {
    result[i] = input.substring(bounderies[i] + 1, bounderies[i + 1]);
    } return result; } public static int[] getBounderies(String input) {
    int[] bounderies = new int[input.length()];
    int bounderyIndex = 0;
    int bracketLeft = 0;
    for (int i = 0; i < input.length(); i++) {
    if (input.charAt(i) == '{') {
    bracketLeft++;
    continue;
    }
    if (input.charAt(i) == '}') {
    bracketLeft--;
    continue;
    }
    if (input.charAt(i) == ',') {
    if (bracketLeft == 1) {
    bounderies[bounderyIndex] = i;
    bounderyIndex++;
    continue;
    }
    }
    }
    bounderies[bounderyIndex] = -1;
    int[] result = new int[bounderyIndex + 2];
    System.arraycopy(bounderies, 0, result, 1, bounderyIndex);

    result[0] = 0;
    result[result.length - 1] = input.length() - 1;
    return result;
    }
    }
      

  3.   

    自己测10w个字符的字符串,处理时间在毫秒级的,两次打印系统时间相同,也就是说在50ms以内
      

  4.   

      String s = "{1,2,{3,4,5},{2,3},4,{3,{4,5},5},3,{1,2,{3,4,5},{2,3},4,{3,{4,5},5},3},6}";
        s=s.substring(1,s.length()-1);
        String[] ss=Pattern.compile("(?<![{][0-9,]{1,1000}),(?=(\\d+$)|(\\d+[^}]+)|(\\{[0-9,{}]+\\}))").split(s);
        
    for(String sa:ss)
        System.out.println(sa);