Java String Split by Quote splitHandleQuotes(String s)

Here you can find the source of splitHandleQuotes(String s)

Description

split Handle Quotes

License

Open Source License

Declaration

private static List<String> splitHandleQuotes(String s) 

Method Source Code

//package com.java2s;
/*// w ww  .  j av a2s.  com
 * Copyright (C) 2009 Emweb bvba, Leuven, Belgium.
 *
 * See the LICENSE file for terms of use.
 */

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

public class Main {
    private static List<String> splitHandleQuotes(String s) {
        ArrayList<String> results = new ArrayList<String>();
        char delimiter = ',';
        char quoteChar = '"';
        char escapeChar = '\\';

        StringBuffer current = new StringBuffer("");
        boolean inQuotation = false;
        boolean escaping = false;

        for (int i = 0; i < s.length(); ++i) {
            if (escaping) {
                if (s.charAt(i) == quoteChar)
                    current.append(quoteChar);
                else {
                    current.append(escapeChar);
                    current.append(quoteChar);
                }
                escaping = false;
            } else {
                if (s.charAt(i) == quoteChar) {
                    inQuotation = !inQuotation;
                } else if (s.charAt(i) == escapeChar) {
                    escaping = true;
                } else if (!inQuotation)
                    if (s.charAt(i) == delimiter) {
                        results.add(new String(current));
                        current = new StringBuffer("");
                    } else
                        current.append(s.charAt(i));
                else
                    current.append(s.charAt(i));
            }
        }

        results.add(new String(current));

        return results;
    }
}

Related

  1. quoteAwareSplit(String str, char delim)
  2. split(String sString, boolean bIgnoreQuotes)
  3. split(String str, char chrSplit, char chrQuote)
  4. splitArrayStringQuoted(String array, char quoteChar)
  5. splitIgnoringQuotes(String str, char separatorChar)
  6. splitIgoringQuotes(String str)
  7. splitOnCharWithQuoting(String s, char splitChar, char quoteChar, char escapeChar)
  8. splitOnCharWithQuoting(String s, char splitChar, char quoteChar, char escapeChar)