title: Matching one string multiple times using regex in Java
body: <p>I'm having some issues with making the following regex work. I would like the following string:</p>
  
  <pre><code>"Please enter your name here"
  </code></pre>
  
  <p>to result in an array with the following elements:</p>
  
  <pre><code>'please enter', 'enter your', 'your name', 'name here'
  </code></pre>
  
  <p>Currently, I'm using the following pattern, and then creating a matcher and iterating in the following way:</p>
  
  <pre><code>Pattern word = Pattern.compile("[\w]+ [\w]+");
  Matcher m = word.matcher("Please enter your name here");
  
  while (m.find()) {
      wordList.add(m.group());
  }
  </code></pre>
  
  <p>But the result I'm getting is:</p>
  
  <pre><code>'please enter', 'your name'
  </code></pre>
  
  <p>What am I doing wrong? (P.s., i checked the same regex on regexpal.com and had the same problem). It seems like the same word won't be matched twice. What can I do to achieve the result I want?</p>
  
  <p>Thanks.</p>
  
  <p><strong>---------------------------------</strong></p>
  
  <p><strong>EDIT:</strong>
  Thanks for all the suggestions! I ended up doing this (because it adds flexibility in being able to easily specify number of "n-grams"):</p>
  
  <pre><code>Integer nGrams = 2;
  String patternTpl = "\\b[\\w']+\\b";
  String concatString = "what is your age? please enter your name."
  for (int i = 0; i &lt; nGrams; i++) {
      // Create pattern.
      String pattern = patternTpl;
      for (int j = 0; j &lt; i; j++) {
          pattern = pattern + " " + patternTpl;
      }
      pattern = "(?=(" + pattern + "))";
      Pattern word = Pattern.compile(pattern);
      Matcher m = word.matcher(concatString);
  
      // Iterate over all words and populate wordList
      while (m.find()) {
          wordList.add(m.group(1));
      }
  }
  </code></pre>
  
  <p>This results in:</p>
  
  <pre><code>Pattern: 
  (?=(\b[\w']+\b)) // In the first iteration
  (?=(\b[\w']+\b \b[\w']+\b)) // In the second iteration
  
  Array:
  [what, is, your, age, please, enter, your, name, what is, is your, your age, please enter, enter your, your name]
  </code></pre>
  
  <p>Note: Got the pattern from the following top answer: <a href="https://stackoverflow.com/questions/13330401/java-regex-skipping-matches?rq=1">Java regex skipping matches</a></p>