title: Java regex for matching multiple keys in a string
body: <p>Consider an input string like</p>
  
  <pre><code>Number ONE=1 appears before TWO=2 and THREE=3 comes before FOUR=4 and FIVE=5
  </code></pre>
  
  <p>and the regular expression</p>
  
  <pre><code>\b(TWO|FOUR)=([^ ]*)\b
  </code></pre>
  
  <p>Using this regular expression, the following code can extract the 2 specific key-value pairs out of the 5 total ones (i.e., only some predefined key-value pairs should be extracted).</p>
  
  <pre><code>  public static void main(String[] args) throws Exception {
      String input = "Number ONE=1 appears before TWO=2 and THREE=3 comes before FOUR=4 and FIVE=5";
      String regex = "\\b(TWO|FOUR)=([^ ]*)\\b";
      Pattern pattern = Pattern.compile(regex);
      Matcher matcher = pattern.matcher(input);
      while (matcher.find()) {
        System.out.println("\t" + matcher.group(1) + " = " + matcher.group(2));
      }
    }
  </code></pre>
  
  <p>More specifically, the <code>main()</code> method above prints</p>
  
  <pre><code>TWO = 2
  FOUR = 4
  </code></pre>
  
  <p>but every time <code>find()</code> is invoked, the whole regular expression is evaluated for the part of the string remaining after the latest match, left to right.</p>
  
  <p>Also, if the keys are not mutually distinct (or, if a regular expression with overlapping matches was used in the place of each key), there will be multiple matches. For instance, if the regex becomes</p>
  
  <pre><code>\b(O.*?|T.*?)=([^ ]*)\b
  </code></pre>
  
  <p>the above method yields</p>
  
  <pre><code>ONE = 1
  TWO = 2
  THREE = 3
  </code></pre>
  
  <p>If the regex was not fully re-evaluated but each alternative part was somehow examined once (or, if an appropriately modified regex was used), the output would have been</p>
  
  <pre><code>ONE = 1
  TWO = 2
  </code></pre>
  
  <p>So, two questions:</p>
  
  <ol>
  <li>Is there a more efficient way of extracting a selected set of unique keys and their values, compared to the original regular expression?</li>
  <li>Is there a regular expression that can match every alternative part of the OR (<code>|</code>) sub-expression exactly once and not evaluate it again?</li>
  </ol>