Here you can find the source of splitBySeparatorQuoteAndParen(String line, char sep)
Parameter | Description |
---|---|
line | the string to split |
sep | the seperator character, e.g. a comma |
public static String[] splitBySeparatorQuoteAndParen(String line, char sep)
//package com.java2s; /*************************************** * ViPER * * The Video Processing * * Evaluation Resource * * * * Distributed under the GPL license * * Terms available at gnu.org. * * * * Copyright University of Maryland, * * College Park. * ***************************************/ import java.util.*; public class Main { /**/*from w w w . j a va2s . c om*/ * Split using a separator, but allow for the separator to occur * in nested parentheses without splitting. * <PRE> * E.g. "1", 2*("2,3"), "4" * would split into * -- "1" * -- 2*("2,3") * -- "4" * </PRE> * If the data has an odd number of "s, it will append a " character * to the end. In order to include a quote character without delimiting * a string, use the \". For a \, use \\. * @param line the string to split * @param sep the seperator character, e.g. a comma * @return the split string */ public static String[] splitBySeparatorQuoteAndParen(String line, char sep) { boolean withinQuotes = false; String newLine = new String(line); Vector temp = new Vector(); StringBuffer nextString = new StringBuffer(); int nesting = 0; for (int i = 0; i < newLine.length(); i++) { char c = newLine.charAt(i); if (c == '\\') { if ((++i >= newLine.length()) && (nextString.length() > 0)) { temp.addElement(nextString.toString()); break; } else { switch (newLine.charAt(i)) { case 'n': nextString.append('\n'); break; case '"': nextString.append('"'); break; default: nextString.append(newLine.charAt(i)); } } } else if (c == '"') { withinQuotes = !withinQuotes; nextString.append('"'); } else if (!withinQuotes) { if (c == '(') { nesting++; nextString.append('('); } else if (c == ')') { nesting--; nextString.append(')'); } else { if ((nesting == 0) && (c == sep)) { temp.addElement(nextString.toString()); nextString.delete(0, nextString.length()); } else { nextString.append(newLine.charAt(i)); } } } else { nextString.append(newLine.charAt(i)); } } if (withinQuotes) { nextString.append('"'); } temp.addElement(nextString.toString()); String[] result = new String[temp.size()]; for (int i = 0; i < result.length; i++) { result[i] = (String) temp.elementAt(i); } return (result); } }