<p>Situation:</p>

<ul>
<li>text:  a string</li>
<li>R:  a regex that matches part of the string.  This might be expensive to calculate.  </li>
</ul>

<p>I want to both delete the R-matches from the text, and see what they actually contain.  Currently, I do this like:</p>

<pre><code>import re
ab_re = re.compile("[ab]")
text="abcdedfe falijbijie bbbb laifsjelifjl"
ab_re.findall(text)
# ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']
ab_re.sub('',text)
# 'cdedfe flijijie  lifsjelifjl'
</code></pre>

<p>This runs the regex twice, near as I can tell.  Is there a technique to do it all on pass, perhaps using re.split?  It seems like with split based solutions I'd need to do the regex at least twice as well.  </p>

You could use split with capturing parantheses.  If you do, then the text of all groups in the pattern are also returned as part of the resulting list (from
python doc
).
So the code would be
```
```
import re
ab_re = re.compile("([ab])")
text="abcdedfe falijbijie bbbb laifsjelifjl"
matches = ab_re.split(text)
# matches = ['', 'a', '', 'b', 'cdedfe f', 'a', 'lij', 'b', 'ijie ', 'b', '', 'b', '', 'b', '', 'b', ' l', 'a', 'ifsjelifjl']

# now extract the matches
Rmatches = []
remaining = []
for i in range(1, len(matches), 2):
    Rmatches.append(matches[i])
# Rmatches = ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']

for i in range(0, len(matches), 2):
    remaining.append(matches[i])
remainingtext = ''.join(remaining)
# remainingtext = 'cdedfe flijijie  lifsjelifjl'
```
```