2

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.

1
  • Something like this: [:\s] ?
    – Laurel
    Nov 19 '16 at 2:09
4

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
1
  • 1
    Thank you! I never heard of a negative/positive lookahead split. Reading up on it. This is exactly what I was looking for. Nov 19 '16 at 2:22
0

The easiest way will just be to do it in two steps:

String str = "PICK TWO IN ORDER: 10 2 T F";
String[] split1 = str.split(":");
String[] split2 = split1[1].trim().split("\\s+");

... with the results being split1[0] and split2.

2
  • I think mine is easier :-)
    – baao
    Nov 19 '16 at 2:19
  • 1
    You're right, it does get to the desired answer more easily :D
    – qxz
    Nov 19 '16 at 2:23
0

You could compile a Pattern, and if it matches, use that to populate an array. Something like,

String sentence = "PICK TWO IN ORDER: 10 2 T F";
Pattern p = Pattern.compile("(.+)\\:\\s+(\\d+)\\s+(\\d+)\\s+([T|F])\\s+([T|F])");
Matcher m = p.matcher(sentence);
String[] Str = null;
if (m.find()) {
    Str = new String[m.groupCount()];
    for (int i = 1; i <= Str.length; i++) {
        Str[i - 1] = m.group(i);
    }
}
System.out.println(Arrays.toString(Str));

Which produces a String[] named Str that matches your request.

[PICK TWO IN ORDER, 10, 2, T, F]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.