Match two groups but none of them should be empty
<p>I want my regex to be able to match strings of random chars optionally followed by some digits - but if both matches are empty I want the match to fail. I am currently constructing the regex as in:</p>

<pre><code>regex = u'^(.*)'
if has_digits: regex += u'(\d*)'
regex += ext + u'$' # extension group as in u'(\.exe)'
rePattern = re.compile(regex, re.I | re.U)
</code></pre>

<p>but this also matches empty filenames (with extension only). Can't wrap my head around similar questions like:</p>

<ul>
<li><a href="http://stackoverflow.com/q/13351990/281545">In a regular expression, match one thing or another, or both</a></li>
<li><a href="http://stackoverflow.com/q/6664015/281545">Matching a group that may or may not exist</a></li>
</ul>

<p>The extra complication is that the second group (the digits) may not be added</p>

<p>So valid:</p>

<pre><code>abc%.exe
123.exe
</code></pre>

<p>If has_digits is true:</p>

<pre><code>abc 123.exe # I want the second group to contain the 123 not the first one
</code></pre>

<p>Invalid : <code>.exe</code></p>

<p>Regex:</p>

<pre><code>^(.*?)(\d+)?(?&lt;=.)\.exe$
</code></pre>

<p>Positive lookbehind assures that there is at least one character before extension part.</p>

<p><strong><a href="https://www.regex101.com/r/CNBQyG/1" rel="nofollow">Live demo</a></strong></p>

<p>Integrated:</p>

<pre><code>regex = '^(.*?)'
if has_digits: regex += '(\d+)?'
regex += '(?&lt;=.)' + ext + '$'
rePattern = re.compile(regex, re.I | re.U)
</code></pre>

python regex python-2.7 regex-lookarounds