title: Regular expression for parsing similar assembler instructions
body: <p>The intro is a bit lengthy, so please bear with me. :)</p>
  
  <p>I am writing a simple regex-based parser for a large source file written in assembler. Most of these instructions are just moving, adding, subtracting and jumping around, but it's a pretty large file which I need to port to two different languages and I am too lazy to do it manually. That's the requirement and I can't do much 'bout it (so please don't answer stuff like "why don't you simply use ANTLR").</p>
  
  <p>So, after I do some preprocessing (I already did this part: replaced defines and macros and stripped redundant whitespace and comments), I now basically have to read the file line by line and parse one or potentially more lines into "intermediate" instructions, which I will then use to generate more or less 1-to-1 equivalent (using actual integer arithmetics and a bunch of GOTOs). </p>
  
  <p>So, presuming that I can have all these different addressing modes:</p>
  
  <p><img src="https://i.stack.imgur.com/U1eiv.png" alt="Addressing mode depends on the format of the instruction"></p>
  
  <p>I can go two different ways:</p>
  
  <ol>
  <li>Have a single MOV regex which will handle all these cases, or</li>
  <li>Have multiple MOV regexes, on for each instruction type. The problem with this approach is that I would have to design each regex pretty carefully to avoid any ambiguity. AND it seems there would be lots of duplicates since source and destination operands share many of the addressing modes.</li>
  </ol>
  
  <p>My question is: If I have a single regex for all instructions, how should I specify my groups and captures to be able to simply differentiate between different modes? </p>
  
  <p>Or do I simply catch everything and then process the source/destination address after the initial match?</p>
  
  <p>E.g. a rather simple match-all regex would be:</p>
  
  <pre><code>^MOV\s+(?&lt;dest&gt;[^\s,]+)[\s,]*(?&lt;src&gt;[^\s,]+)$
  </code></pre>
  
  <p>(Split into multiple lines with comments):</p>
  
  <pre><code>^MOV              (?#instruction)
  \s+               (?#some whitespace)
  (?&lt;dest&gt;[^\s,]+)  (?#match everything except whitespace and comma)
  \s*,\s*           (?#match comma, allow some whitespace)
  (?&lt;src&gt;[^\s,]+)   (?#match everything except whitespace and comma)$
  </code></pre>
  
  <p>So, I can certainly do this and then process <code>dest</code> and <code>src</code> groups separately. But would it be better to create a nasty complex regex to match all cases from the table below? In that case I am not sure how I would interpret these captures to understand what addressing mode was matched.</p>
  
  <p>I am using C#, if that makes any difference.</p>