title: Parse pipe seperated string (Pipes can be escaped ) in Java
body: <p>Receive a pipe separated parameter, need to tokenize it; but pipes can be escaped with \| to indicate its not a seperator, but part of the token. I know the Java compiler does this with strings we have " and escaped quotes \" in a string literal.</p>
  
  <p>But not sure of a good utility function/ algorithm to tokenize such a string. Output will be a List of strings.</p>
  
  <p>Sample Input 1: <code>"jk|g4"</code>, output : <code>"jk" , "g4"</code> (list with 2 strings)</p>
  
  <p>Sample Input 2: <code>"j\|k|g4|b"</code>, output : <code>"j|k" , "g4", "b"</code> (list with 3 strings and literal pipe)</p>
  
  <p>Tried using <code>String.indexOf("|")</code>, then checking the previous character if its a \ ... but have errors and wanted to make sure : is there is an easier way? Regex?</p>
  
  <p>Here is what I have :</p>
  
  <pre><code>import java.util.ArrayList;
  import java.util.List;
  
  public class PasrePipes {
      public static void main(String[] args) {
  
          String in = "j\\|k|g4|b";
          {
              String[] ex = { "j|k", "g4", "b" };
              tst(in, ex);
          }
  
          in = "j|k|g4|b";
          {
              String[] ex = { "j", "k", "g4", "b" };
              tst(in, ex);
          }
      }
  
      private static void tst(String in, String[] ex) {
          System.out.println("----\n" + in);
          List&lt;String&gt; toks = parse(in);
          if (toks.size() != ex.length) {
              System.out.println("size mismatch, got :" + toks.size() + " exp " + ex.length);
          }
          for (int i = 0; i &lt; ex.length; i++) {
              if (toks.size() &gt; i) {
                  String n = toks.get(i);
                  if (!ex[i].equals(n)) {
                      System.out.println(" mismatch :" + i + ", got :" + n + "; exp :" + ex[i]);
                  } else {
                      System.out.println(" okay :" + i + "; exp :" + ex[i]);
                  }
              }
          }
  
          System.out.println("--");
      }
  
      private static List&lt;String&gt; parse(String in) {
          List&lt;String&gt; tokens = new ArrayList&lt;String&gt;();
          int i = in.indexOf('|');
          int old = 0;
  
          while (i &gt; -1) {
              if (i &gt; 0) {
                  if (in.charAt(i - 1) == '\\') {
                      i = in.indexOf('|', i + 1);
                      continue;
                  }
              }
              String s = in.substring(old, i);
              s.replace("\\|", "|");
              tokens.add(s);
              old = i + 1;
              i = in.indexOf('|', i + 1);
  
          }
          if(i &gt; 0 &amp;&amp; i &lt; (in.length() - 1)) {
              String s = in.substring(i + 1);
              s.replace("\\|", "|");
              tokens.add(s);
          }
          return tokens;
  
      }
  }
  </code></pre>