Referencing named groups in look-around (Python 2.x)
<p>I have a pattern that matches for <em>multiple</em> key/value pairs, and the key/value strings can be delimited by any characters, then the groups of key/value can also be delimited, just <strong>not by the same character</strong>.</p>

<p>I figured out how to allow dynamic delimiters, and restrict the same delimiter from being used twice. EG:</p>

<pre><code>\w+(?P&lt;kv_delim&gt;[:;|])\d+(?P&lt;g_delim&gt;(?!(?P=kv_delim))[:;|])\w(?P=kv_delim)\d(?P=g_delim)?
</code></pre>

<p><a href="https://regex101.com/r/qC7hQ2/3" rel="nofollow">You can view the regex101.com example here</a>. And it works great, the problem comes when using either of the two named groups in a <em>positive look-behind</em>.</p>

<p>Lets say the string is</p>

<blockquote>
  <p><code>foo:1;r:2</code></p>
</blockquote>

<p>The "key/value delimiter" (named group: <code>kv_delim</code>) is the <code>:</code>, then the "group delimiter" (named group: <code>grp_delim</code>) is the <code>;</code></p>

<p>What im trying to do is dynamically match the <code>:</code> and <code>;</code>, then in a look-around statement, look for <code>foo&lt;kv_delim&gt;</code>, or <code>bar&lt;kv_delim&gt;</code>.</p>

<p>If I hard-code the delimiters (in the look-around), <a href="https://regex101.com/r/uM6bL8/3" rel="nofollow">you can see it works</a>. But if I try to reference the named-group <code>kv_delim</code> within the look-around statement, <a href="https://regex101.com/r/bA6dM6/2" rel="nofollow">you can see it throws errors</a>. I get the error:</p>

<blockquote>
  <p>Subpattern references are not allowed within a lookbehind assertion</p>
</blockquote>

<p>Which is whats kickin my butt</p>

<p>Anybody have a way to make this work?</p>

<p>Thanks!</p>

<p>Summing up what has already been said: the point is that the length of the pattern is unknown when you put backreferences into a lookbehind that <a href="https://docs.python.org/3/library/re.html#regular-expression-syntax" rel="nofollow">must be fixed-width</a> at design time. The newer <a href="https://pypi.python.org/pypi/regex" rel="nofollow">PyPi <code>regex</code> module</a> has no limitations regarding the lookbehind length, so, the current workaround is to use this module with your regex:</p>

<pre><code>&gt;&gt;&gt; import regex
&gt;&gt;&gt; s = "foo:1;r:2"
&gt;&gt;&gt; rx = r"\w+(?P&lt;kv_delim&gt;[:;|])\d+(?P&lt;g_delim&gt;(?!(?P=kv_delim))[:;|])\w(?P=kv_delim)\d(?P=g_delim)?"
&gt;&gt;&gt; print(regex.findall(rx, s))
[(':', ';')]
&gt;&gt;&gt; print([m.group() for m in regex.finditer(rx, s)])
['foo:1;r:2']
&gt;&gt;&gt; 
</code></pre>

python regex regex-lookarounds regex-greedy