title: Non-greedy search in lpeg without consuming the end match
body: <p>This was spun off from the comments on <a href="https://stackoverflow.com/questions/70661539/opening-and-closing-elements-in-lpeg-for-pandoc-reader">this question</a>.</p>
  <p>As I understand, in the PEG grammar, it's possible to implement a non-greedy search by writing <code>S &lt;- E2 / E1 S</code> (or S = pattern E2 if possible or pattern E1 and continued S).</p>
  <p>However, I don't want to capture E2 in the final pattern - I want to capture <em>up to</em> E2. When trying to implement this in LPEG I've run into several issues, including 'Empty loop in rule' errors when building this into a grammar.</p>
  <p>How would we implement the following search in a LPEG grammar: <code>[tag] foo [/tag]</code> where we want to capture the contents of the tag in a capture table ('foo' in the example), but we want to terminate before the ending tag? As I understand from the comments on the other question, this should be possible, but I can't find an example in LPEG.</p>
  <p>Here's a snippet from the test grammar</p>
  <pre class="lang-lua prettyprint-override"><code>local tag_start = P&quot;[tag]&quot;
  local tag_end = P&quot;[/tag]&quot;
  
  G = P{'Pandoc', 
    ...
    NotTag = #tag_end + P&quot;1&quot; * V&quot;NotTag&quot;^0;
    ...
    tag = tag_start * Ct(V&quot;NotTag&quot;^0) * tag_end;
  }
  </code></pre>