2013-06-24 191 views
4

我对Java很陌生。 我想知道是否有一个更简单而高效的方式来实现下面的字符串分割。我尝试过使用模式和匹配器,但并没有按照我想要的方式出现。由{}分割字符串&[]

"{1,24,5,[8,5,9],7,[0,1]}" 

拆分成:

1 
24 
5 
[8,5,9] 
7 
[0,1] 

这是一个完全错误的代码,但我无论如何张贴:

String str = "{1,24,5,[8,5,9],7,[0,1]}"; 
    str= str.replaceAll("\\{", ""); 
    str= str.replaceAll("}", ""); 
    Pattern pattern = Pattern.compile("\\[(.*?)\\]"); 
    Matcher matcher = pattern.matcher(str); 
    String[] test = new String[10]; 
    // String[] _test = new String[10]; 
    int i = 0; 
    String[] split = str.split(","); 

    while (matcher.find()) { 


     test[i] = matcher.group(0); 
     String[] split1 = matcher.group(0).split(","); 


     // System.out.println(split1[i]); 
      for (int j = 0; j < split.length; j++) { 
      if(!split[j].equals(test[j])&&((!split[j].contains("\\["))||!split[j].contains("\\]"))){ 
       System.out.println(split[j]); 
      } 

     } 
     i++; 


    } 

} 

对于给定的字符串格式让说{A, b,[c,d,e],...}格式。我想征集所有内容,但方括号内的内容将被表示为一个元素(如数组)。

+7

你可以发布你已经尝试过的代码? –

+0

是GSON的数据吗? –

+0

@AndrewThompson为什么选择这个标题? OP从未说过他想分裂成多维int数组,他说他只是想分割字符串... – BackSlash

回答

6

这工作:

public static void main(String[] args) 
    { 
    customSplit("{1,24,5,[8,5,9],7,[0,1]}"); 
    } 


    static void customSplit(String str){ 
    Pattern pattern = Pattern.compile("[0-9]+|\\[.*?\\]"); 
    Matcher matcher = 
      pattern.matcher(str); 
    while (matcher.find()) { 
     System.out.println(matcher.group()); 
    } 
    } 

产生了输出

1 
24 
5 
[8,5,9] 
7 
[0,1] 
+0

完美。谢谢:) – user2516389

+2

很好的解决方案。请注意@ user2516389,尽管这样做不会检查列表整体是否由'{'/'}'花括号包围,并且“嵌套数组”可以包含任何内容。例如,对于输入''garberge在开始5,[8,foo,5,9],7}}}''输出是'5','[8,foo,5,9]','7'每个都在自己的路线上)。另一个例子,“{2,3},4,5”产生“2 3 4 5”,“{2,3} 4,5”也产生。 –