1

I am trying to split a string to array string with all the letter as name at beginning (sometimes the name has many words) in array string.

Simple:

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

result should looks like this:

[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]

Code:

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+");
        }

How can fix it?

I appreciate any help.

Mr Asker
  • 2,300
  • 11
  • 31
  • 56
  • http://stackoverflow.com/q/1102891/1415929 could be useful. Maybe split the parent string by white space, test if numeric, if not then build a new string for your 0th array element. If it is numeric, process as necessary and append to array. – IdusOrtus Jun 07 '15 at 22:20

1 Answers1

0

Here is the code you can use:

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));
}

See IDEONE demo

Output:

[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]
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563