Regex - Conditional replace if captured group exists
<p>Suppose I have the following 2 strings representing phone numbers:</p>

<ol>
<li>1112223333</li>
<li>11122233334</li>
</ol>

<p>The first one is for a normal phone number <code>(111) 222-3333</code> and the second one is for a phone number with an extension <code>(111) 222-3333 ext 4</code></p>

<p>So we know the phone number will always be 10 digits and possibly 11. If it is 11, then I'd like it formatted with the second version.</p>

<p>My current regex and replace are as follows:</p>

<p><strong>Regex:</strong> <code>(\d{3})(\d{3})(\d{4})(\d?)</code></p>

<p><strong>Replacement:</strong> <code>($1) $2-$3 ext $4</code></p>

<p>Which works, except that regardless whether the 4th capturing group exists or not, I get the "ext" added in, so I get:</p>

<ol>
<li><p><code>1112223333</code>  > <code>(111) 222-3333 ext</code> (should be <code>(111) 222-3333</code> (no "ext" suffix)</p></li>
<li><p><code>11122233334</code> > <code>(111) 222-3333 ext 4</code> (correct)</p></li>
</ol>

<p>I know I can do this via code / evaluating matches (I'm programming in C# / .Net), but I'm more curious to know <em>if there a way to change the replacement regex itself</em> to have some form of logic to only add the suffix <code>ext $4</code> if and only if there was a 4th capturing group?</p>