title: Regex to capture named groups in any order
body: <p>I have a scenario in which I need to use a single call to Python's re.sub() to find and replace items in a string.  If that constraint sounds contrived, just consider this a mental exercise, but know that it is a real-life constraint I have to work with.</p>
  
  <p>I want to match and replace a line like either of these:</p>
  
  <pre><code>foo -some-arg -o %output %input
  foo %input -other-random-arg=baz -o %output
  </code></pre>
  
  <p>with this:</p>
  
  <pre><code>bar %output %input.out
  </code></pre>
  
  <p>The file names %input and %output can be anything matching <code>[a-zA-Z0-9._-]+</code> but are always preceded by <code>%</code></p>
  
  <p>I came up with this substitution which does not quite work.</p>
  
  <pre><code>    r'''(?x)                     # Begin verbose regex
          foo[ ]                   # foo and a space
          (?=.*?-o[ ]                  # Lookahead for the first occurrence of -o
              (?P&lt;a&gt;%\S+\b)                # Output filename -&gt; Group 'a'
          )
          (?=.*?                       # Lookahead from the same place as the first lookahead
                                       # so the two filenames can match in any order.
              (?!-o[ ]%\S+\b)              # Do not match the output file
              (?P&lt;b&gt;%\S+\b)                # Any filename -&gt; Group 'b'
          ).*                      # Match anything ''',
      r'bar \g&lt;b&gt; \g&lt;a&gt;.out'       # Replacement
  </code></pre>
  
  <p>I often end up with one of the two file names repeated twice like:</p>
  
  <pre><code>bar %output %output.out
  </code></pre>
  
  <p>Is there a way to named-capture the two file names in whatever order they appear?  It seems that if I could advance the regex engine's pointer upon matching the one of the lookaheads, I could make this work.</p>