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

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 {
    /** Splits a string based on spaces, grouping atoms if they are inside non escaped double quotes.
     *//* ww w.j  a  v a  2s.co  m*/
    static public List<String> splitQuotedString(String str) {
        List<String> strings = new ArrayList<String>();
        boolean inQuotes = false;
        boolean quoteStateChange = false;
        StringBuffer buffer = new StringBuffer();
        //Find some spaces, 
        for (int i = 0; i < str.length(); i++) {
            //Have we toggled the quote state?
            char c = str.charAt(i);
            quoteStateChange = false;
            if (c == '"' && (i == 0 || str.charAt(i - 1) != '\\')) {
                inQuotes = !inQuotes;
                quoteStateChange = true;
            }
            //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 we're not in quotes, and we've hit a space...
            if (!inQuotes && str.charAt(i) == ' ') {
                //Do we actually have somthing in the buffer?
                if (buffer.length() > 0) {
                    strings.add(buffer.toString());
                    buffer.setLength(0);
                }
            } else if (!quoteStateChange) {
                //We only want to add stuff to the buffer if we're forced to by quotes, or we're not a "
                buffer.append(c);
            }
        }
        //Add on the last string if needed
        if (buffer.length() > 0) {
            strings.add(buffer.toString());
        }

        return strings;
    }
}

Related

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