title: Extract all occurrences of pattern K and check if string matches "K*" in 1 pass
body: <p>For a given input string and a given pattern K, I want to extract every occurrence of K (or some part of it (using groups)) from the string <strong>and</strong> check that the entire string matches <code>K*</code> (as in it consists of 0 or more K's with no other characters).</p>
  
  <p>But I would like to do this <strong>in a single pass</strong> using regular expressions. More specifically, I'm currently finding the pattern using <code>Matcher.find</code>, but this is not strictly required.</p>
  
  <p>How would I do this?</p>
  
  <p>I already found a solution (and posted an answer), but would like to know if there is specific regex or <code>Matcher</code> functionality that addresses / can address this issue, or simply if there are better / different ways of doing it. But, even if not, I still think it's an interesting question.</p>
  
  <p><strong>Example:</strong></p>
  
  <p>Pattern: <code>&lt;[0-9]&gt;</code> (a single digit in <code>&lt;&gt;</code>)</p>
  
  <p>Valid input: <code>&lt;1&gt;&lt;2&gt;&lt;3&gt;</code></p>
  
  <p>Invalid inputs:</p>
  
  <pre><code>&lt;1&gt;&lt;2&gt;a&lt;3&gt;
  &lt;1&gt;&lt;2&gt;3
  Oh look, a flying monkey!
  &lt;1&gt;&lt;2&gt;&lt;3
  </code></pre>
  
  <p><strong>Code to do it in 2 passes with <code>matches</code>:</strong></p>
  
  <pre><code>boolean products(String products)
  {
      String regex = "(&lt;[0-9]&gt;)";
      Pattern pAll = Pattern.compile(regex + "*");
  
      if (!pAll.matcher(products).matches())
          return false;
  
      Pattern p = Pattern.compile(regex);
      Matcher matcher = p.matcher(products);
  
      while (matcher.find())
          System.out.println(matcher.group());
  
      return true;
  }
  </code></pre>