Here you can find the source of splitInitialItems(final String text)
Parameter | Description |
---|---|
text | Text to parse, may be <code>null</code> or empty |
Parameter | Description |
---|---|
Exception | on error |
null
if nothing provided
public static List<String> splitInitialItems(final String text) throws Exception
//package com.java2s; /******************************************************************************* * Copyright (c) 2016 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ import java.util.ArrayList; import java.util.List; public class Main { /** Split initial value text into items. */*from w w w . j a va2 s . c o m*/ * <p>Items are separated by comma. * Items are trimmed of surrounding whitespace. * * <p>Spaces and commata inside quotes are retained. * Quotes inside quotes need to be escaped. * * @param text Text to parse, may be <code>null</code> or empty * @return Items from text, <code>null</code> if nothing provided * @throws Exception on error */ public static List<String> splitInitialItems(final String text) throws Exception { if (text == null || text.isEmpty()) return null; final List<String> items = new ArrayList<>(); int pos = 0; while (pos < text.length()) { final char c = text.charAt(pos); // Skip space if (c == ' ' || c == '\t') ++pos; // Handle quoted string else if (c == '"') { // Locate closing, non-escaped quote int end = text.indexOf('"', pos + 1); while (end > pos && text.charAt(end - 1) == '\\') end = text.indexOf('"', end + 1); if (end < 0) throw new Exception("Missing closing quote"); items.add(text.substring(pos, end + 1)); pos = end + 1; // Advance to comma at end of string while (pos < text.length() && text.charAt(pos) != ',') ++pos; ++pos; } // Handle unquoted item else { // Locate comma int end = pos + 1; while (end < text.length() && text.charAt(end) != ',') ++end; items.add(text.substring(pos, end).trim()); pos = end + 1; } } return items; } }