title: Regex Matching shortest match instead of longest
body: <p>I am trying to write regex but having trouble making it work for some cases. Here is the regex</p>
  
  <pre><code>(\/[ABCGIKLNPRSUV])?(\/RC-[A-Z0-9]{2,6})?
  </code></pre>
  
  <p>The matches could be one of the following</p>
  
  <ul>
  <li>/R/RC-ABC123</li>
  <li>/R</li>
  <li>/RC-ABC123</li>
  </ul>
  
  <p>The above regex works for /R and /R/RC-ABC123 but not /RC-ABC123. For /RC-ABC123, it keeps matching against the first group instead of the second group and only takes /R as the matched component.</p>
  
  <p>How can I make it work for all the cases.  Also, the above expression is only a part of the full expression i.e. there could be another (third) group after RC-ABC123. But want to get it working for these 2 groups first.</p>
  
  <p><strong>Update</strong>
  The ?? seems to work in regex101 but not in java. I get 2 groups but with null values for /R/RC-ABC123 using the following code</p>
  
  <pre><code>Pattern pattern = Pattern.compile("(/[A-Z])??(/RC-[A-Z0-9]{2,6})?");
      Matcher matcher = pattern.matcher("/R/RC-ABC12345");
      if(matcher.find()) {
          for(int i=1; i&lt;= matcher.groupCount(); i++) {
              System.out.println("Group("+i+") = " + matcher.group(i));
          }
      }else {
          System.out.println("Pattern does not match");
      }
  </code></pre>