2015-06-07 36 views
1

我想將字符串拆分爲數組字符串,並將所有字母都作爲數組字符串中的開始名稱(有時名稱有很多單詞)。將字符串拆分爲數組帶字符串的名字在第一個位置

簡單:

car water apple 04:48 05:18 05:46 06:16 06:46 07:16 07:46 
bridge night 04:57 05:27 05:56 06:26 06:56 07:26 07:56 

結果應該看起來像這樣:

[car water apple, 04:48 05:18 05:46 06:16 06:46 07:16 07:46 ] 
[bridge night, 04:57 05:27 05:56 06:26 06:56 07:26 07:56] 

代碼:

if (line.contains(":") && min_value > 0) { 
      // With this regular expression I am getting it without `car water apple` 
      String[] newLine = line.replaceFirst(
        "(?m)^.*?(?=\\d+:\\d+)", "").split("\\s+"); 
     } 

如何解決它?

我感謝所有幫助。

+0

http://stackoverflow.com/q/1102891/1415929可能是有用的。也許用空格分割父字符串,測試是否爲數字,如果不是,則爲第0個數組元素構建一個新字符串。如果它是數字,則根據需要進行處理並追加到數組中。 – IdusOrtus

回答

0

這裏是你可以使用代碼:

String line = "car water apple 04:48 05:18 05:46 06:16 06:46 07:16 07:46\nbridge night 04:57 05:27 05:56 06:26 06:56 07:26 07:56"; 
List<String[]> allMatches = new ArrayList<String[]>(); 
Matcher m = Pattern.compile("(?m)^(.*?)\\s*((?:\\d+:\\d+\\s*)*)$") 
     .matcher(line); 
while (m.find()) { 
    allMatches.add(new String[] { m.group(1), m.group(2)}); 
} 

for(String[] object: allMatches){ 
    System.out.println(Arrays.toString(object)); 
} 

IDEONE demo

輸出:

[car water apple, 04:48 05:18 05:46 06:16 06:46 07:16 07:46] 
[bridge night, 04:57 05:27 05:56 06:26 06:56 07:26 07:56] 
+0

它對你有用嗎?還是需要進一步的幫助? –