Split and keep deliminator, preferably with regex
<p>Let's say I have this text:</p>

<pre><code>1.1 This is the 2,1 first 1.2 This is the 2,2 second 1.3 This is the 2,3 third 
</code></pre>

<p>and I want:</p>

<pre><code>["1.1 This is the 2,1 first","1.2 This is the 2,2 second","1.3 This is the 2,3 third"]
</code></pre>

<p>Note that:</p>

<ul>
<li><p>I  can't use <code>re.findall</code>, since I can't think of a way to properly terminate the match. The best I could think of was <code>'[0-9]+\.[0-9]+^([0-9]+\.[0-9]+)*'</code>, which didn't work.</p></li>
<li><p>I can't just store the delimiter as a global variable, since it changes with each match.</p></li>
<li><p>I could not use a regular <code>re.split</code> because I want to keep the delimiter. I can't use a lookbehind because it has to be fixed width, and this isn't.</p></li>
</ul>

<p>I have read <a href="http://stackoverflow.com/questions/18323764/regexp-split-and-keep-the-seperator">regexp split and keep the seperator</a>, <a href="http://stackoverflow.com/questions/7866128/python-split-without-removing-the-delimiter">Python split() without removing the delimiter</a>, and <a href="http://stackoverflow.com/questions/2136556/in-python-how-do-i-split-a-string-and-keep-the-separators">In Python, how do I split a string and keep the separators?</a>, and still don't have an answer.</p>

<p>Yes, you can:</p>

<pre><code>\b\d+\.\d+
.+?(?=\d+\.\d+|$)
</code></pre>

<p>See it <a href="https://regex101.com/r/ABNxgQ/1" rel="nofollow"><strong>working on regex101.com</strong></a>. To be used in addition to <code>re.findall()</code>:</p>

<pre><code>import re
rx = re.compile(r'\b\d+\.\d+.+?(?=\d+\.\d+|$)')
string = "1.1 This is the 2,1 first 1.2 This is the 2,2 second 1.3 This is the 2,3 third "
matches = rx.findall(string)
print(matches)
# ['1.1 This is the 2,1 first ', '1.2 This is the 2,2 second ', '1.3 This is the 2,3 third ']
</code></pre>

<p>If the string spans across multiple lines, use either the <strong>dotall mode</strong> or <code>[\s\S]*?</code>.<br>
See <a href="http://ideone.com/HXe4Tb" rel="nofollow"><strong>a demo on ideone.com</strong></a>.</p>

python regex