2017-01-09 40 views
-3

,我試圖分裂的字符串如下:如何將字符串拆分爲具有拆分和正則表達式的數組?

#1 Single" (2006)\t\t\t\t\t2006-???? 

我努力的正則表達式是:

(["#0-9 a-zA-Z]*\w") (\([0-9]*\w\)).*([0-9{4}]*\d-[\?0-9{4}]*) 

然而,這需要整個字符串,而不是部分。 我如何使它成爲一個數組?

array("\"#1 Single\"", "2006", "2006-????"); 
+0

應該採取什麼'陣列() '爲什麼不用'split()'方法?如果字符串的結構對於「簡單」拆分過於複雜,請嘗試'Pattern'和'Matcher'以及'group()'方法和簡單的數組/集合操作。 – Thomas

+0

正如托馬斯所說,使用'Matcher'的'''屬性來獲取單個匹配組的值。 –

回答

2

您在正則表達式已經分組你感興趣的不同部位,所以你應該單獨獲取並使用它們來填充結果數組:

//assumes a Matcher matcher which has already matched the text with .find() or .matches() 
int groupCount = 3; // for more complex cases, use matcher.groupCount(); 
String[] parts = new String[groupCount]; 
for (int groupIndex = 0; groupIndex < groupCount; groupIndex++) { 
    parts[groupIndex] = matcher.group(groupIndex); 
} 
相關問題