title: A Regular Expression with a Conditional in Lookbehind
body: <p>This is using the .NET regex engine.</p>
  
  <p>I am attempting to use a conditional inside of a lookbehind clause.  When the expression is used outside of the lookbehind it behaves as I expect -- but when placed in the lookbehind, it has a different behavior.</p>
  
  <p>Here is a simple example of the effect to try to duplicate the issue.  </p>
  
  <p>Matching:</p>
  
  <pre><code>good morning
  </code></pre>
  
  <p>with the regular expression:</p>
  
  <pre><code>(?&lt;=(?(?=go)good|bad)\s)morning
  </code></pre>
  
  <p>yields no match.</p>
  
  <p>When tried without the look behind:</p>
  
  <pre><code>(?(?=go)good|bad)\smorning
  </code></pre>
  
  <p>I get a match on "good morning"</p>
  
  <p>By fiddling around, I discovered that the lookahead cursor location, when it is inside the lookbehind, is after the word "good":</p>
  
  <pre><code>(?&lt;=(?(?=\smor)good|bad)\s)morning
  </code></pre>
  
  <p>This matches "morning".</p>
  
  <p>My question is is this expected or some kind of bug?</p>
  
  <p>Obviously this example is not real world - the problem that I was trying to solve when I stumbled on this issue is as follows:  The expression uses a conditional to determine the length of the next word, then uses two different sets of rules for matching on that word.  Similar to:</p>
  
  <pre><code>(?&lt;=\s+(?(?=[^\s]{1,2}\s)[A-Z0-9]+|(?![A-Z]+\s)[0-9-A-Z/"']+))\s+matching\s+text
  </code></pre>
  
  <p>This matches the "matching text" only if a one or two letter word consisting of letters and numbers, or a longer word not consisting of only letters but can contain numbers, letters, slashes, dashes, quotes and apostrophes.</p>
  
  <p>The following should match "matching text":</p>
  
  <pre><code>1 matching text
  a matching text
  </code></pre>
  
  <p>It only matches on the first one, because the conditional evaluated to false (it was looking at the " matching" instead of "a") and the negative look ahead searching for a word consisting of all letters failed on the "a".</p>
  
  <p>Further examples:</p>
  
  <p>Must match "matching text":</p>
  
  <pre><code>123-1 matching text
  9B matching text
  15/16 matching text
  "45" matching text
  A matching text
  AA matching text
  A1 matching text
  </code></pre>
  
  <p>Must not match "matching text"</p>
  
  <pre><code>and matching text
  " matching text
  A- matching text
  </code></pre>