Java String Split by Quote splitQuotedString(String str)

Here you can find the source of splitQuotedString(String str)

Description

Splits a string based on spaces, grouping atoms if they are inside non escaped double quotes.

License

Open Source License

Parameter

Parameter Description
str The string to split.

Return

The list of split strings.

Declaration

static public List<String> splitQuotedString(String str) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**/*from   w w w.j a v a  2s  .c  o  m*/
     * Splits a string based on spaces, grouping atoms if they are inside non escaped double quotes.
     *
     * @param str The string to split.
     * @return The list of split strings.
     */
    static public List<String> splitQuotedString(String str) {
        List<String> strings = new ArrayList<String>();
        int level = 0;
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == '"') {
                if (i == 0 || str.charAt(i - 1) == ' ') {
                    // start quote
                    level++;
                    // don't need to append quotes for top-level things
                    if (level == 1)
                        continue;
                }
                if (i == str.length() - 1 || str.charAt(i + 1) == ' ' || str.charAt(i + 1) == '"') {
                    // end quote
                    level--;
                    if (level == 0)
                        continue;
                }
            }
            //Peek at the next character - if we have a \", we need to only insert a "
            if (c == '\\' && i < str.length() - 1 && str.charAt(i + 1) == '"') {
                c = '"';
                i++;
            }

            if (level == 0 && str.charAt(i) == ' ') {
                // done with this part
                if (buffer.length() > 0) {
                    strings.add(buffer.toString());
                    buffer.setLength(0);
                }
            } else {
                buffer.append(c);
            }
        }
        //Add on the last string if needed
        if (buffer.length() > 0) {
            strings.add(buffer.toString());
        }

        return strings;
    }
}

Related

  1. splitOptions(String quotedOptionString)
  2. splitQuoted(String input, Character split)
  3. splitQuoted(String str, char delimiter)
  4. splitQuotedEscape(String src)
  5. splitQuotedStr(String str, char delimiter, char quote, boolean trim)
  6. splitQuotedString(String str)
  7. splitQuotedTokens(String str)
  8. splitSafeQuote(String input, char separator)
  9. splitShifted(int[] shiftedQuoteString)