meanrims
meanrims

Reputation: 65

Regex for splitting up strings (Java)

I have a single string which looks like:

6
0 1 1 0 0
1 1 1 1 0
0 0 0 1 0
4
1 1 0 1 0
0 0 0 1 0
1 1 0 1 0
0 1 1 0 0

and would like to split into two different strings such as:

6
0 1 1 0 0
1 1 1 1 0
0 0 0 1 0

and the other string being:

4
1 1 0 1 0
0 0 0 1 0
1 1 0 1 0
0 1 1 0 0

Would I do this using regex? Or is there a better way? note: apart from the 6 and 4 the others numbers will always be 1 or 0.

Upvotes: 2

Views: 109

Answers (4)

Bohemian
Bohemian

Reputation: 425033

You want to split on newlines, but only when the following character(s) is only digit(s) then a newline.
Try this regex:

"\n(?=\\d+\\n)"

It uses a look ahead to assert the condition mentioned above.

Here's some test code:

public static void main(String[] args) {
    String input = "6\n0 1 1 0 0\n1 1 1 1 0\n0 0 0 1 0\n4\n1 1 0 1 0\n0 0 0 1 0\n1 1 0 1 0\n0 1 1 0 0";
    String[] parts = input.split("\n(?=\\d+\\n)");
    System.out.println(Arrays.toString(parts));
}

Output:

[6
0 1 1 0 0
1 1 1 1 0
0 0 0 1 0, 4
1 1 0 1 0
0 0 0 1 0
1 1 0 1 0
0 1 1 0 0]

Upvotes: 4

Denis Tulskiy
Denis Tulskiy

Reputation: 19177

You can definitely do it with regex, as answered by @Bohemian. But only if you're not going to do any other processing on the result. If you're need to parse split strings any further, and if you use regex again, it's gonna make your code too complicated. I'd rather recommend you to send the string to a java.util.Scanner and parse the whole string into some more usable data structure or set of classes for future use.

Upvotes: 1

Sai Dubbaka
Sai Dubbaka

Reputation: 621

Yes it would require regexp. You can create a java.util.regex.Pattern.compile("([64][^64]+?)", Pattern.MULTILINE) and create a java.util.regex.Matcher out of it and starting find()ing through your CharSequence. You can query for group(1) each time you find() something.

Upvotes: -1

Mohsen Afshin
Mohsen Afshin

Reputation: 13436

It's possible without regex:

String phrase = 
"6
0 1 1 0 0
1 1 1 1 0
0 0 0 1 0
4
1 1 0 1 0
0 0 0 1 0
1 1 0 1 0
0 1 1 0 0";

String delims = "[4 6]+";

String[] parts= phrase.split(delims);

Upvotes: -2

Related Questions