Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The first <code>.*</code> initially matches the whole string. Then the regex engine determines whether it needs to back off to match the rest of the regex. But <code>(?&lt;h&gt;((dog)*))</code> and <code>(?(h)(?&lt;dog&gt;(.*)))</code> can both legally match zero characters, so no backtracking is needed (as far as the <code>.*</code> is concerned). Try using a non-greedy <code>.*?</code> in that part.</p> <p><strong>EDIT (in response to the additional info posted in the answer below):</strong> Okay, replacing the first <code>.*</code> with a non-greedy <code>.*?</code> <em>does</em> have an effect, just not the one you want. Where everything after the word "cool" was being captured in group <code>&lt;cool&gt;</code> before, now it's being captured in group <code>&lt;dog&gt;</code>. Here's what's happening:</p> <p>After the word "cool" is matched, <code>(?&lt;cool&gt;(.*?))</code> initially matches nothing (the opposite of the greedy behavior), and <code>(?&lt;h&gt;((dog)*))</code> tries to match. This part <em>will always succeed</em> no matter where it's tried, because it can match either "dog" or an empty string. That means the conditional expression in <code>(?(h)...)</code> will always evaluate to <code>true</code>, so it goes ahead and matches the rest of the input with <code>(?&lt;dog&gt;(.*))</code>.</p> <p>As I understand it, you want to match everything after "cool" in named group <code>&lt;cool&gt;</code>, unless the string contains the word "dog"; then you want to capture everything after "dog" in named group <code>&lt;dog&gt;</code>. You're trying to use a <a href="http://www.regular-expressions.info/conditional.html" rel="nofollow noreferrer">conditional</a> for that, but it's not really the right tool. Just do this:</p> <pre><code>string pattern = @"cool (?&lt;cool&gt;.*?) (dog (?&lt;dog&gt;.*))?$"; </code></pre> <p>The key here is the <code>$</code> at the end; it forces the non-greedy <code>.*?</code> to keep matching until it reaches the end of the string. Because it's non-greedy, it tries to match the next part of the regex, <code>(dog (?&lt;dog&gt;.*))</code>, before consuming each character. If the word "dog" is there, the rest of the string will be consumed by <code>(?&lt;dog&gt;.*)</code>; if not, the regex still succeeds because the <code>?</code> makes that whole part optional.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload