title: How does backtracking work in peg.js (with example)?
body: <p>I've defined the following minimal Peg.js grammar:</p>
  
  <pre><code>start  =  "A1" / "A123"
  </code></pre>
  
  <p>which you can try <a href="http://pegjs.majda.cz/online" rel="noreferrer">in the sandbox</a>. </p>
  
  <p>I would have expected to match "A1" as well as "A123" (according to my notion of how backtracking works). But this is not the case: the grammar recognizes "A1" but not "A123".</p>
  
  <p><strong>Note</strong>: I am not looking for the advice "reverse the order of your terms" as in the related question <a href="https://stackoverflow.com/questions/13160281/how-to-transform-a-simple-grammar-into-something-which-works-in-peg-js-expected">How to transform a simple grammar into something which works in PEG.js (expected &quot;a&quot; but &quot;a&quot; found)</a>. Rather, I'm looking to understand the behavior I'm seeing, and why Peg.js's backtracking doesn't apply in this case. For an explanation of why reversing the order of my terms doesn't help, see the more realistic example below.</p>
  
  <hr>
  
  <p>For a more realistic example, consider units parsing. A grammar should recognize metric units (like "m", "mol") with optional prefixes, like "mm", "mmol", as well as non-metric units like "yr", "week", or "mo".</p>
  
  <p>The following Peg.js grammar won't recognize "mol" because it gets tripped up consuming "mo", and doesn't backtrack. (Changing the order of terms doesn't help; or rather, will cause "mo" to be recognized at the expense of "mol" or "mmol".)</p>
  
  <pre><code>start  =  nonmetric / metric / prefix metric
  metric = "mol" / "l" / "m" / "g"
  nonmetric = "yr" / "mo" / "week" / "day" / "hour"
  prefix = "m" / "k" / "c"
  </code></pre>
  
  <p>I can do the analagous thing in Antlr with good success:</p>
  
  <pre><code>grammar units;
  start  :  nonmetric | metric | prefix metric;
  metric : 'mol' | 'l' | 'm' | 'g';
  nonmetric : 'yr' | 'mo' | 'week' | 'day' | 'hour';
  prefix : 'm' | 'k' | 'c';
  </code></pre>