2011-11-09 131 views
3

,如果我有一個字符串格式:的Java在Java中分割字符串

(string1 , string2) (string2) (string4 , string5 , string6) [s2] 

我如何分割字符串得到的字符串數組作爲呢?

string1 , string2 
string2 
string4 , string5 , string6 
+2

你想串的單個陣​​列或字符串數​​組的數組? – Daan

回答

6

試試這個:

String test = "(string1 , string2) (string2) (string4 , string5 , string6) [s2]"; 

    String[] splits = test.split("\\(\\s*|\\)[^\\(]*\\(?\\s*"); 

    for (String split : splits) { 
     System.out.println(split); 
    } 
+0

+1'split()'在概念上稍微簡單一些,但是我可以添加一點來匹配關閉括號之前的任何空白以及打開後的空白,或者刪除匹配所有空白的空白。 –

3

您可以用一根火柴:

List<String> matchList = new ArrayList<String>(); 
Pattern regex = Pattern.compile("\\((.*?)\\)"); 
Matcher regexMatcher = regex.matcher(subjectString); 
while (regexMatcher.find()) { 
    matchList.add(regexMatcher.group(1)); 
} 

匹配(之間的任何東西),並將其存儲到反向引用1.

說明:

"\\(" +  // Match the character 「(」 literally 
"(" +  // Match the regular expression below and capture its match into backreference number 1 
    "." +  // Match any single character that is not a line break character 
     "*?" +  // Between zero and unlimited times, as few times as possible, expanding as needed (lazy) 
")" + 
"\\)"  // Match the character 「)」 literally 
0

你可能想在/\(.+?\)/使用分 - 這樣的事情在Java:

Pattern p = Pattern.compile("\\(.+?\\)"); 
Matcher m = p.matcher(myString); 
ArrayList<String> ar = new ArrayList<String>(); 
while (m.find()) { 
    ar.add(m.group()); 
} 
String[] result = new String[ar.size()]; 
result = ar.toArray(result);