Java String Split by Delimiter splitWithEscapeChar(String s, char delimiter, char escape)

Here you can find the source of splitWithEscapeChar(String s, char delimiter, char escape)

Description

Split a string 's' using 'delimiter' but don't split on any delimiters escaped with 'escape' character.

License

Open Source License

Declaration

public static List<String> splitWithEscapeChar(String s, char delimiter, char escape) 

Method Source Code

//package com.java2s;
/*/*from   ww w .j  a  va2  s  . co m*/
 * All GTAS code is Copyright 2016, Unisys Corporation.
 * 
 * Please see LICENSE.txt for details.
 */

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

public class Main {
    /**
     * Split a string 's' using 'delimiter' but don't split on any delimiters
     * escaped with 'escape' character.  For example, if we call this method
     * with s = "mc?'foo'bar", delimiter = '\'', escape = '?'  the method
     * should return ["mc'foo", "bar"].  Note as a side-effect, the escape
     * characters are removed from the final output.
     */
    public static List<String> splitWithEscapeChar(String s, char delimiter, char escape) {
        String escapedDelimiter = String.format("\\%c\\%c", escape, delimiter);
        final String sentinel = "~XYZ~";
        String tmp = s.replaceAll(escapedDelimiter, sentinel);

        String regex = String.format("\\%c", delimiter);
        String[] tmpSplit = tmp.split(regex);
        List<String> rv = new ArrayList<>(tmpSplit.length);
        for (String myString : tmpSplit) {
            rv.add(myString.replaceAll(sentinel, "\\" + delimiter).trim());
        }

        return rv;
    }
}

Related

  1. splitToList(String a_text, String a_delimiter)
  2. splitToList(String s, String delimRegEx)
  3. splitToList(String str, char delimiter)
  4. splitUpTo(String s, String delimiter, int cnt)
  5. splitWhileKeepingParentheses(String value, char delimiter)
  6. stringSplitter(String inStr, String delimiterStr)
  7. tokenizerSplit(String string, String delimiter)
  8. toTextArray(String text, String delimiter)