title: Regular Expressions: Match up to an optional word
body: <p>Need to match the first part of a sentence, up to a given word. However, that word is optional, in which case I want to match the whole sentence.  For example:</p>
  <blockquote>
  <p>I have a sentence with a clause I don't want.</p>
  </blockquote>
  <blockquote>
  <p>I have a sentence and I like it.</p>
  </blockquote>
  <p>In the first case, I want <code>&quot;I have a sentence&quot;</code>. In the second case, I want <code>&quot;I have a sentence and I like it.&quot;</code></p>
  <p>Lookarounds will give me the first case, but as soon as I try to make it optional, to cover the second case, I get the whole first sentence.  I've tried making the expression lazy... no dice.</p>
  <p>The code that works for the first case:</p>
  <pre><code>var regEx = new Regex(@&quot;.*(?=with)&quot;);
  string matchstr = @&quot;I have a sentence with a clause I don't want&quot;;
  
  if (regEx.IsMatch(matchstr)) {
      Console.WriteLine(regEx.Match(matchstr).Captures[0].Value);
      Console.WriteLine(&quot;Matched!&quot;);
  }
  else {
      Console.WriteLine(&quot;Not Matched : (&quot;);
  }
  </code></pre>
  <p>The expression that I wish worked:</p>
  <pre><code>var regEx = new Regex(@&quot;.*(?=with)?&quot;);
  </code></pre>
  <p>Any suggestions?</p>