Frank
Frank

Reputation: 31086

How to split multi-line string in Java

I have the following data text :

[data]A[/data]
aaa
4 5 8 
[data]B[/data]
bbb
3 1 9 
[data]C[/data]
ccc
6 5 2
... 

I want to split them in to the following 3 units :

1st unit :

[data]A[/data]
aaa
4 5 8 

2nd unit :

[data]B[/data]
bbb
3 1 9 

3rd unit :

[data]C[/data]
ccc
6 5 2

So my code looks like this :

String Units[]=dataText.split("[data]");

Yet, this doesn't do it properly, what's the right way to split it ?

If I use regex, how should I write the expression ?

Upvotes: 0

Views: 778

Answers (2)

Christian Huber
Christian Huber

Reputation: 818

You could use a BufferedReader:

BufferedReader br = new BufferedReader(new StringReader(dataString));

Iterate the String like this:

int lineCounter = 0;
int arrayCounter = 0;
String line = null;
while( (line = br.readLine()) != null )
{
    units[arrayCounter] += line;
    if (lineCounter >= 2) {
        arrayCounter++;
        lineCounter = 0;
    }
}

Upvotes: 1

Andreas
Andreas

Reputation: 159086

Use regex (?ms)(?<=.)(?=^\[):

    String[] units = dataText.split("(?ms)(?<=.)(?=^\\[)");

See regex101.com for demo.

Explanation:

(?ms)       Turn on MULTILINE ('^' and '$' match after/before line terminator)
                and DOTALL (aka "single line", '.' matches any character)
(?<=.)      Must be preceded by a character (needs 's' flag)
               Used to prevent matching very first '['
(?=^\[)     Must be followed by a '[' at the beginning of a line (needs 'm' flag)

Upvotes: 3

Related Questions