title: Java -- Patterns -- Matcher.group()?
body: <p>So I have a document, and a specified n-gram target string. I'm trying to find the indexes of all occurrences of the target string. </p>
  
  <pre><code>final Pattern WORD_PATTERN = Pattern.compile("\\w+");
  Matcher matcher = WORD_PATTERN.matcher("the lazy dog, jumps, the lazy dog.");
  </code></pre>
  
  <p>So the string is "the lazy dog, jumps, the lazy dog."</p>
  
  <p>Say my target n-gram is "the lazy". I essentially 'iterate' through the entire string as follows, adding 'n' words to a linked list, currentNGram. If all of the words in currentNGram match the target n-gram, I save the index. Else, I remove the first element of the linked list, and append on the next word in the input string (eg. check the next successive n-gram in the document).</p>
  
  <pre><code>while (matcher.find()) {
      while (currentNGram.size() &lt; lengthOfTargetNTuple) { 
          currentNGram.add(matcher.group().toLowerCase());
              System.out.println(currentNGram.getLast());
      }
  }
  </code></pre>
  
  <p>So that's all fine and dandy, but my next problem is that I have to 'iterate' through the document again, and find the distance of every n-gram to the nearest target n-gram. So I take the exact same approach. Except this time, when I reinitialize the matcher, and run the loop as follows,</p>
  
  <pre><code> while (matcher.find()) {
          while (currentGram.size() &lt; lengthOfTargetNTuple) {
              currentGram.add(matcher.group().toLowerCase());
                      System.out.println(currentGram.printLast()) // Psuedocode
          }
  </code></pre>
  
  <p>it prints the word "the" 7 times instead of printing "the" "lazy" "dog" "jumps", etc. However, </p>
  
  <pre><code>while (matcher.find()) {
          while (currentGram.size() &lt; lengthOfTargetNTuple) {
              currentGram.add(matcher.group().toLowerCase());
          }
          System.out.println(matcher.group()); // Prints words in order, correctly
  }
  </code></pre>
  
  <p>Why is this? How come the matcher.group() method call printed out words in their correct order in the first problem, but not the second? Any direction would be greatly appreciated; I know this was a long post, sorry.</p>
  
  <p>Thanks!</p>