在你回答我ansumption在評論你的狀態,你正在做這樣的事情:
String[] array = new String[]{"AA", "BB", "CC", "DD" };
String[] elems = Arrays.toString(array).split(",");
for(String e : elems) {
System.out.println(e); //and here you try to get rid of the brackets
}
這似乎是一種錯誤的方式(不知道你的代碼,但是有99%的把握是)。僅僅過了直接的元素循環:
String[] array = new String[]{"AA", "BB", "CC", "DD" };
for(String e : array) {
System.out.println(e);
}
除非你正在做一些完全不同的(你沒有告訴我們)沒有必要先使用Arrays.toString()
,然後再次分裂。即使數組元素不是字符串,但System.out.println()
會使用元素的toString()
方法,就像Arrays.toString()
會做的那樣。
編輯:根據你的評論,你從某個位置得到一些字符串,基本上是[ [xxx/AA, xxx/BB], [xxx/CC] ]
的形式。使用String.split()
這裏可能是錯誤的方法,因爲您可能會保留分組等。
假設嵌套在所有情況下都保持不變,即有喜歡[ [ [ xxx/AA ], [xxx/BB] ] ]
沒有額外的分組,我建議採用兩步法使用正則表達式:
Pattern groupsPattern = Pattern.compile("\\[([^\\[]+?)\\]");
Pattern contentPattern= Pattern.compile("/([^,/]+)\\s*(?:,|$)");
//Step 1: look for groups of text in square brackets,
//i.e. look for "xxx, yyy" in "[xxx, yyy]"
Matcher groupsMatcher = groupsPattern.matcher(input);
while(groupsMatcher.find()) {
//Step 2: extract the values you're looking for from the group
String groupContent = groupsMatcher.group(1);
//here you could split on commas or use another pattern, which I'll do
Matcher contentMatcher = contentPattern.matcher(groupContent);
while(contentMatcher.find()) {
System.out.println(contentMatcher.group(1));
}
}
表達的短故障:
\[([^\[]+?)\]
[^\[]+?
意味着最短至少一個字符的序列不是一個[
(...)
捕獲上述作爲1組(0總是整個匹配)
\[...\]
要求組由方括號
/([^,/]+)\s*(?:,|$)
([^,/]+)
包圍裝置的至少一個字符的任何序列,其是不是一個逗號或斜線和捕獲作爲組1
\s*
指空白的任何序列(可以是無)
(?:,|$)
是非易失捕獲與逗號匹配的組或匹配輸入的末尾,意味着:捕獲至少一個不是逗號或斜線的字符的任何序列,其前面是斜線,後面跟隨任何空格和逗號或輸入的結尾
如何打印數組?從一開始,這可能是錯誤的,也就是說,我假設你使用'Arrays.toString()'然後分割結果 - 而不是去這裏。 – Thomas
什麼是您的陣列actully包含以及如何嘗試迭代請添加更多有關數組的信息(您要打印) –
請源代碼。 –