title: Bug in Java regex implementation?
body: <p>I've identified some unexpected behavior in Java's regex implementation. When using <a href="http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html"><code>java.util.regex.Pattern</code></a> and <a href="http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html"><code>java.util.regex.Matcher</code></a>, the following regular expression <em>does not</em> match correctly on the input <code>"Merlot"</code> when using Matcher's <a href="http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#find%28%29"><code>find()</code></a> method:</p>
  
  <pre class="lang-none prettyprint-override"><code>((?:White )?Zinfandel|Merlot)
  </code></pre>
  
  <p>If I change the order of the expressions inside the outermost matching group, Matcher's <a href="http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#find%28%29"><code>find()</code></a> method <em>does</em> match.</p>
  
  <pre class="lang-none prettyprint-override"><code>(Merlot|(?:White )?Zinfandel)
  </code></pre>
  
  <p>Here is some test code that illustrates the problem.</p>
  
  <h2>RegexTest.java</h2>
  
  <pre><code>import java.util.regex.*;
  
  public class RegexTest {
      public static void main(String[] args) {
          Pattern pattern1 = Pattern.compile("((?:White )?Zinfandel|Merlot)");
          Matcher matcher1 = pattern1.matcher("Merlot");
          // prints "No Match :("
          if (matcher1.find()) {
              System.out.println(matcher1.group(0));
          } else {
              System.out.println("No match :(");
          }
  
          Pattern pattern2 = Pattern.compile("(Merlot|(?:White )?Zinfandel)");
          Matcher matcher2 = pattern2.matcher("Merlot");
          // prints "Merlot"
          if (matcher2.find()) {
              System.out.println(matcher2.group(0));
          } else {
              System.out.println("No match :(");
          }
      }
  }
  </code></pre>
  
  <p>The expected output is:</p>
  
  <pre class="lang-none prettyprint-override"><code>Merlot
  Merlot
  </code></pre>
  
  <p>But the actual output is:</p>
  
  <pre class="lang-none prettyprint-override"><code>No Match :(
  Merlot
  </code></pre>
  
  <p>I've verified this unexpected behavior exists in Java version 1.7.0_11 on Ubuntu linux and also Java version 1.6.0_37 on OSX 10.8.2. I reported this behavior as a bug to <a href="http://bugs.sun.com">Oracle</a> yesterday and got back an automated email telling me my bug report has been received and has an internal review ID of 2441589. I can't find my bug report when I search for that id in their bug database. (Can you hear the crickets?)</p>
  
  <p>Have I uncovered a bug in Java's presumably thoroughly tested and used regex implementation (hard to believe in 2013), or am I doing something wrong?</p>