title: Regular expression: who's greedier?
body: <p>My primary concern is with the Java flavor, but I'd also appreciate information regarding others.</p>
  
  <p>Let's say you have a subpattern like this:</p>
  
  <pre><code>(.*)(.*)
  </code></pre>
  
  <p>Not very useful as is, but let's say these two capture groups (say, <code>\1</code> and <code>\2</code>) are part of a bigger pattern that matches with backreferences to these groups, etc.</p>
  
  <p>So both are greedy, in that they try to capture as much as possible, only taking less when they have to.</p>
  
  <p>My question is: who's greedier? Does <code>\1</code> get first priority, giving <code>\2</code> its share only if it has to?</p>
  
  <p>What about:</p>
  
  <pre><code>(.*)(.*)(.*)
  </code></pre>
  
  <p>Let's assume that <code>\1</code> does get first priority. Let's say it got too greedy, and then spit out a character. Who gets it first? Is it always <code>\2</code> or can it be <code>\3</code>?</p>
  
  <p>Let's assume it's <code>\2</code> that gets <code>\1</code>'s rejection. If this still doesn't work, who spits out now? Does <code>\2</code> spit to <code>\3</code>, or does <code>\1</code> spit out another to <code>\2</code> first?</p>
  
  <hr>
  
  <h3>Bonus question</h3>
  
  <p>What happens if you write something like this:</p>
  
  <pre><code>(.*)(.*?)(.*)
  </code></pre>
  
  <p>Now <code>\2</code> is reluctant. Does that mean <code>\1</code> spits out to <code>\3</code>, and <code>\2</code> only reluctantly accepts <code>\3</code>'s rejection?</p>
  
  <hr>
  
  <h3>Example</h3>
  
  <p>Maybe it was a mistake for me not to give concrete examples to show how I'm using these patterns, but here's some:</p>
  
  <pre><code>System.out.println(
      "OhMyGod=MyMyMyOhGodOhGodOhGod"
      .replaceAll("^(.*)(.*)(.*)=(\\1|\\2|\\3)+$", "&lt;$1&gt;&lt;$2&gt;&lt;$3&gt;")
  ); // prints "&lt;Oh&gt;&lt;My&gt;&lt;God&gt;"
  
  // same pattern, different input string
  System.out.println(
      "OhMyGod=OhMyGodOhOhOh"
      .replaceAll("^(.*)(.*)(.*)=(\\1|\\2|\\3)+$", "&lt;$1&gt;&lt;$2&gt;&lt;$3&gt;")
  ); // prints "&lt;Oh&gt;&lt;MyGod&gt;&lt;&gt;"
  
  // now \2 is reluctant
  System.out.println(
      "OhMyGod=OhMyGodOhOhOh"
      .replaceAll("^(.*)(.*?)(.*)=(\\1|\\2|\\3)+$", "&lt;$1&gt;&lt;$2&gt;&lt;$3&gt;")
  ); // prints "&lt;Oh&gt;&lt;&gt;&lt;MyGod&gt;"
  </code></pre>