Concrete line break into brackets

I would like to split the line as follows:

String s = "dotimes [sum 1 2] [dotimes [sum 1 2] [sum 1 3]]"

Result:

{"dotimes", "[sum 1 2]", "[dotimes [sum 1 2] [sum 1 3]]" 

I tried using this regex:

s.split("\\s(?=\\[)|(?<=\\])\\s")

But this leads to the following:

dotimes

[sum 1 2]

[dotimes

[sum 1 2]

[sum 1 3]]

Is there a way to split the string the way I want to use regex?

+4
source share
2 answers

This works, although not particularly nicely, and in the absence of formal grammar from the OP, it may work poorly in generalization.

{
    //String s = "sum 1 2";
    String s = "dotimes [sum 1 2] [dotimes [sum 1 2] [sum 1 3]]";
    int depth = 0;
    int pos = 0;        
    for (int c = 0; c <= s.length(); ++c){
        switch (c == s.length() ? ' ' : s.charAt(c)){
        case '[':
            if (++depth == 1){
                pos = c;
            }
            break;
        case ' ':
            if (depth == 0){
                String token = s.substring(pos, c == s.length() ? c : c + 1);
                if (!token.matches("\\s*")){ /*ingore white space*/
                    System.out.println(token);
                }                            
                pos = c + 1;
            }
            break;
        case ']':
            if (--depth == 0){
                String token = s.substring(pos, c + 1);
                if (!token.matches("\\s*")){ /*ingore white space*/
                    System.out.println(token);
                }                                                        
                pos = c + 1;
            }
        break;
        }
    }        
}

It writes a split line to standard output; add to your favorite container as you please.

0
source

Is there a way to split the string the way I want to use regex?

, . ( ) , (), , . , .

Java, . Java, java-:

Array match_children (Array input) {
    Array output;

    foreach (match in input) {
        // The most important part!
        // The string starts with "[", so it is the beginning of a new nest
        if (match.startsWith("[")) {
            // Use the same ragex as below
            Array parents = string.match(matches 'dotimes' and all between '[' and ']');

            // Now, call this same function again with the 
            match = match_children(parents);
            // This stores an array in `match`
        }

        // Store match in output list
        output.push(match);

    }

    return output;
}

String string = "dotimes [sum 1 2] [dotimes [sum 1 2] [sum 1 3]]";
// "dotimes [sum 1 2] [dotimes [sum 1 2] [sum 1 3]]"

Array parents = string.match(matches 'dotimes' and all between '[' and ']');
// "dotimes", "[sum 1 2]", "[dotimes [sum 1 2] [sum 1 3]]"
// Make sure to use a global flag

Array result = match_children(Array input);
// dotimes
// [
//      sum 1 2
// ]
// [
//  dotimes
//  [
//      sum 1 2
//  ]
//  [
//      sum 1 3
//  ]
// ]

, Java, , .:) , .

0

All Articles