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] ? Commented Nov 19, 2016 at 2:09

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I never heard of a negative/positive lookahead split. Reading up on it. This is exactly what I was looking for.
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]

Comments

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 Comments

I think mine is easier :-)
You're right, it does get to the desired answer more easily :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.