Java String Split by Quote quoteAwareSplit(String str, char delim)

Here you can find the source of quoteAwareSplit(String str, char delim)

Description

Break str into individual elements, splitting on delim (not in quotes).

License

Open Source License

Declaration

static List<String> quoteAwareSplit(String str, char delim) 

Method Source Code

//package com.java2s;
/*//from   w w w. j ava  2 s.  c  o m
 *  Copyright (c) 2017, salesforce.com, inc.
 *  All rights reserved.
 *  Licensed under the BSD 3-Clause license.
 *  For full license text, see LICENSE.txt file in the repo root  or https://opensource.org/licenses/BSD-3-Clause
 */

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

public class Main {
    /**
     * Break str into individual elements, splitting on delim (not in quotes).
     */
    static List<String> quoteAwareSplit(String str, char delim) {
        boolean inQuotes = false;
        boolean inEscape = false;

        List<String> elements = new ArrayList<>();
        StringBuilder buffer = new StringBuilder();
        for (char c : str.toCharArray()) {
            if (c == delim && !inQuotes) {
                elements.add(buffer.toString());
                buffer.setLength(0); // clear
                inEscape = false;
                continue;
            }

            if (c == '"') {
                if (inQuotes) {
                    if (!inEscape) {
                        inQuotes = false;
                    }
                } else {
                    inQuotes = true;

                }
                inEscape = false;
                buffer.append(c);
                continue;
            }

            if (c == '\\') {
                if (!inEscape) {
                    inEscape = true;
                    buffer.append(c);
                    continue;
                }
            }

            // all other characters
            inEscape = false;
            buffer.append(c);
        }

        if (inQuotes) {
            throw new RuntimeException("Quoted string not closed");
        }

        elements.add(buffer.toString());

        return elements;
    }
}

Related

  1. split(String sString, boolean bIgnoreQuotes)
  2. split(String str, char chrSplit, char chrQuote)
  3. splitArrayStringQuoted(String array, char quoteChar)
  4. splitHandleQuotes(String s)