title: Regular Expression capturing group with optional delimiter
body: <p>Seemed like a simple problem, I need to extract a capturing group and optionally limit the group with a delimiting string.</p>
  
  <p>In the below example, I provide a delimiting string of 'cd' and expect that it would return 'ab' in all of the cases: 'ab', 'abcd', and 'abcdefg'</p>
  
  <p>Here is the code:</p>
  
  <pre><code>public static void main(String[] args) {
      String expected = "ab"; // Could be more or less than two characters
      String[] tests = {"ab", "abcd", "abcdefg"};
      Pattern pattern = Pattern.compile("(.*)cd?.*");
  
      for(String test : tests) {
          Matcher match = pattern.matcher(test);
          if(match.matches()) {
              if(expected.equals(match.group(1)))
                  System.out.println("Capture Group for test: " + test + " - " + match.group(1));
              else System.err.println("Expected " + expected + " but captured " + match.group(1));
          } else System.err.println("No match for " + test);
      }
  }
  </code></pre>
  
  <p>The output is:</p>
  
  <pre><code>
      No match for ab
      Capture Group for test: abcd - ab
      Capture Group for test: abcdefg - ab
  </code></pre>
  
  <p>I thought that a lookahead might work, but I don't think that there is one that is optional (i.e. zero or more instances)</p>