ButtahNBred ButtahNBred - 17 days ago 5
Java Question

Java RegEx split method

I am looking to split the string "PICK TWO IN ORDER: 10 2 T F" into the following 5 sections.

Str[0] = "PICK TWO IN ORDER"
Str[1] = 10
Str[2] = 2
Str[3] = T
Str[4] = F


I can get the string to split into two parts where it's the string "PICK TWO IN ORDER" and "10 2 T F" by using the regular expression "(:)". However, I cannot seem to figure out how to split the second part. When using the "\s" to split based on spaces it splits the first part into it's four parts.

Is there anyway to limit what part of the string the regular expression parses? Or do I have to use this as a two step process and split them accordingly?

Thanks.

Answer

You can use a negative lookahead in your split to only split on whitespace after the :.

String s = "PICK TWO IN ORDER: 10 2 T F";
String[] foo = s.split(":\\s|\\s(?!.*:)");

Output:

PICK TWO IN ORDER
10
2
T
F