Java String Split by Line splitByBrackets(String line)

Here you can find the source of splitByBrackets(String line)

Description

Extracts a list of all strings contained within brackets.

License

GNU General Public License

Parameter

Parameter Description
line The data to be split.

Exception

Parameter Description
IllegalArgumentException if brackets are unbalanced

Return

An Array containing the Strings inside the brackets.

Declaration

public static String[] splitByBrackets(String line) 

Method Source Code

//package com.java2s;
/***************************************
 *            ViPER                    *
 *  The Video Processing               *
 *         Evaluation Resource         *
 *                                     *
 *  Distributed under the GPL license  *
 *        Terms available at gnu.org.  *
 *                                     *
 *  Copyright University of Maryland,  *
 *                      College Park.  *
 ***************************************/

import java.util.*;

public class Main {
    /**/*w  ww. ja  v  a 2s.c  om*/
     * Extracts a list of all strings contained within brackets.
     * Assumes list contains bracketed elements, as in:
     * <pre>
     *   [ foo ]  [1.2 1.2] [hi]
     * </pre>
     * This will return {" foo ", "1.2 1.2", "hi"}.
     *
     * @param line The data to be split.
     * @throws IllegalArgumentException if brackets are unbalanced
     * @return An Array containing the Strings inside the brackets.
     */
    public static String[] splitByBrackets(String line) {
        if (line == null) {
            return (new String[0]);
        }
        int start = 0;
        int state = 0;
        List L = new LinkedList();
        for (int i = 0; i < line.length(); i++) {
            char c = line.charAt(i);
            if (c == '[') {
                if (0 == state++) {
                    start = i + 1;
                }
            } else if (c == ']') {
                if (0 == --state) {
                    L.add(line.substring(start, i));
                }
                if (state < 0) {
                    throw new IllegalArgumentException("Found unexpected end bracket in string: " + line);
                }
            }
        }
        if (state > 0) {
            throw new IllegalArgumentException("String requires balanced brackets: " + line);
        }
        return (String[]) L.toArray(new String[L.size()]);
    }
}

Related

  1. split(String line, String separator)
  2. split(String line, String seperator)
  3. Split(String line, String sptr)
  4. splitArguments(String commandLine, boolean backslashesAreLiteral)
  5. splitArgumentsBackslashesAreLiteral(String commandLine)
  6. splitBySeparator(String line, char sep)
  7. splitBySeparatorAndParen(String line, char sep)
  8. splitBySeparatorQuoteAndParen(String line, char sep)
  9. splitCommandLine(String str, boolean extract)