2017-01-09 43 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); 
} 
相关问题