title: Split a string in Java based on a separator unless separator is escaped with String.split
body: <p>I got a string in java that I would like to split in parts on following criteria:</p>
  
  <ul>
  <li>the '#' char is a separator</li>
  <li>if  '#' is escaped via backslash then is should not be considered a separator</li>
  </ul>
  
  <p>i.e.</p>
  
  <blockquote>
    <p>"abc#xyz#kml\#ijk"</p>
  </blockquote>
  
  <p>should be split into </p>
  
  <blockquote>
    <p>"abc", "xyz", "kml\#ijk"</p>
  </blockquote>
  
  <p>I can do it easily with StringTokenizer and add some logic for the escape char but I would like to get it via one-liner String.split call with the correct regex. So far my "best" attempt is following:</p>
  
  <pre><code>public static void main(String[] args) {
  
    String toSplit = "abc#xyz#kml\\#ijk";
  
    String[] arr = toSplit.split("[^\\\\]#");
  
    System.out.println(Arrays.toString(arr));
  }
  </code></pre>
  
  <p>and the result is:</p>
  
  <blockquote>
    <p>[ab, xy, kml#ijk]</p>
  </blockquote>
  
  <p>The last letter of the first two parts is cut out. </p>
  
  <p>Any idea how to avoid that?</p>