title: Python re.split and attaching matched group to either right or left side of the split
body: <p>From this example:</p>
  
  <pre><code>&gt;&gt;&gt; re.split('(\W)', 'foo/bar spam\neggs')
  ['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs']
  </code></pre>
  
  <p>is there a straightforward way to associate the capture group with either the right or left portion of the split? E.g. using the same regex/capture group, but yielding:</p>
  
  <pre><code>['foo', '/bar', ' spam', '\neggs']
  </code></pre>
  
  <p>or optionally</p>
  
  <pre><code>['foo/', 'bar ', 'spam\n', 'eggs']
  </code></pre>
  
  <p>I'm sure you can achieve it by <em>changing</em> the actual regex, but that's not the point (and we could modify the example to make the matches more complicated, so that it's a real pain to be unable to just re-use them and push them to the right or left).</p>
  
  <p>Unfortunately it looks like making it a non-capturing group just drops the corresponding characters from the match:</p>
  
  <pre><code>&gt;&gt;&gt; re.split('(?:\W)', 'foo/bar spam\neggs')
  ['foo', 'bar', 'spam', 'eggs']
  </code></pre>
  
  <p>By way of another example, consider if you had some text from a misbehaved CSV file. Each line only has one actual comma to split by, but accidentally some lines also have a comma in one of the fields. Luckily, the non-splitting commas are always followed by a space.</p>
  
  <pre><code>csv_data = [
      'Some good data,Id 5',
      'Some bad data, like, really bad, dude,Id 6'
  ]
  </code></pre>
  
  <p>The goal in this case is to process this into:</p>
  
  <pre><code>[['Some good data', 'Id 5'],
   ['Some bad data, like, really bad, dude', 'Id 6']]
  </code></pre>
  
  <p>through the use of a simple <code>re.split</code>.</p>
  
  <p>Using <code>map(lambda x: re.split(",(?:\S)", x), csv_data)</code> produces</p>
  
  <pre><code>[['Some good data', 'd 5'], 
   ['Some bad data, like, really bad, dude', 'd 6']]
  </code></pre>
  
  <p>and using <code>map(lambda x: re.split(",(\S)", x), csv_data)</code> produces</p>
  
  <pre><code>[['Some good data', 'I', 'd 5'],
   ['Some bad data, like, really bad, dude', 'I', 'd 6']]
  </code></pre>
  
  <p>So what is a generic approach to <code>re.split</code> that would work the same for both of these cases? Basically something I could wrap in a function, like</p>
  
  <pre><code>def my_split(regex_chars, my_strs):
      return map(lambda x: re.split(...regex_chars..., x), my_strs)
  </code></pre>
  
  <p>such that both </p>
  
  <pre><code>my_split(r'(\W)', ['foo/bar spam\neggs']) 
  </code></pre>
  
  <p>and </p>
  
  <pre><code>my_split(r',(\S)', csv_data) 
  </code></pre>
  
  <p>each returns the expected output as from above.</p>
  
  <p><em>Note</em>: It appears this is not possible in just <code>re</code>, but could be possible with some mixture of <code>regex</code> and <code>re</code> based on whether the split is zero-width or not.</p>