Java String Split by Quote splitOptions(String quotedOptionString)

Here you can find the source of splitOptions(String quotedOptionString)

Description

Split up a string containing options into an array of strings, one for each option.

License

Open Source License

Parameter

Parameter Description
quotedOptionString the string containing the options

Exception

Parameter Description
Exception in case of an unterminated string, unknown character ora parse error

Return

the array of options

Declaration

public static String[] splitOptions(String quotedOptionString) throws Exception 

Method Source Code


//package com.java2s;
/*/*from ww  w.j  av a 2s.  c om*/
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.ArrayList;
import java.util.List;

public class Main {
    /**
     * Split up a string containing options into an array of strings,
     * one for each option.
     *
     * @param       quotedOptionString the string containing the options
     * @return       the array of options
     * @throws Exception    in case of an unterminated string, unknown character or
     *          a parse error
     */
    public static String[] splitOptions(String quotedOptionString) throws Exception {
        List<String> result;
        StringBuilder str;
        int i;
        String optStr;

        result = new ArrayList<>();
        str = new StringBuilder(quotedOptionString);

        while (true) {
            // trimLeft
            i = 0;
            while ((i < str.length()) && (Character.isWhitespace(str.charAt(i))))
                i++;
            str = str.delete(0, i);

            // stop when str is empty
            if (str.length() == 0)
                break;

            // if str start with a double quote
            if (str.charAt(0) == '"') {
                // find the first not anti-slashed double quote
                i = 1;
                while (i < str.length()) {
                    if (str.charAt(i) == str.charAt(0))
                        break;
                    if (str.charAt(i) == '\\') {
                        i += 1;
                        if (i >= str.length())
                            throw new Exception("String should not finish with \\");
                    }
                    i += 1;
                }

                if (i >= str.length())
                    throw new Exception("Quote parse error.");

                // add the found string to the option vector (without quotes)
                optStr = str.substring(1, i);
                optStr = unbackQuoteChars(optStr);
                result.add(optStr);
                str = str.delete(0, i + 1);
            } else {
                // find first whiteSpace
                i = 0;
                while ((i < str.length()) && (!Character.isWhitespace(str.charAt(i))))
                    i++;

                // add the found string to the option vector
                optStr = str.substring(0, i);
                result.add(optStr);
                str = str.delete(0, i);
            }
        }

        return result.toArray(new String[result.size()]);
    }

    /**
     * The inverse operation of backQuoteChars().
     * Converts the specified strings into their character representations.
     *
     * @param string    the string
     * @param find   the string to find
     * @param replace   the character equivalents of the strings
     * @return       the converted string
     * @see      #backQuoteChars(String, char[], String[])
     */
    public static String unbackQuoteChars(String string, String[] find, char[] replace) {
        int index;
        StringBuilder newStr;
        int[] pos;
        int curPos;
        String str;
        int i;

        if (string == null)
            return null;

        pos = new int[find.length];

        str = new String(string);
        newStr = new StringBuilder();
        while (str.length() > 0) {
            // get positions and closest character to replace
            curPos = str.length();
            index = -1;
            for (i = 0; i < pos.length; i++) {
                pos[i] = str.indexOf(find[i]);
                if ((pos[i] > -1) && (pos[i] < curPos)) {
                    index = i;
                    curPos = pos[i];
                }
            }

            // replace character if found, otherwise finished
            if (index == -1) {
                newStr.append(str);
                str = "";
            } else {
                newStr.append(str.substring(0, pos[index]));
                newStr.append(replace[index]);
                str = str.substring(pos[index] + find[index].length());
            }
        }

        return newStr.toString();
    }

    /**
     * The inverse operation of backQuoteChars().
     * Converts back-quoted carriage returns and new lines in a string
     * to the corresponding character ('\r' and '\n').
     * Also "un"-back-quotes the following characters: ` " \ \t and %
     *
     * @param string    the string
     * @return       the converted string
     * @see      #backQuoteChars(String)
     */
    public static String unbackQuoteChars(String string) {
        return unbackQuoteChars(string, new String[] { "\\\\", "\\'", "\\t", "\\n", "\\r", "\\\"" },
                new char[] { '\\', '\'', '\t', '\n', '\r', '"' });
    }
}

Related

  1. splitHandleQuotes(String s)
  2. splitIgnoringQuotes(String str, char separatorChar)
  3. splitIgoringQuotes(String str)
  4. splitOnCharWithQuoting(String s, char splitChar, char quoteChar, char escapeChar)
  5. splitOnCharWithQuoting(String s, char splitChar, char quoteChar, char escapeChar)
  6. splitQuoted(String input, Character split)
  7. splitQuoted(String str, char delimiter)
  8. splitQuotedEscape(String src)
  9. splitQuotedStr(String str, char delimiter, char quote, boolean trim)