title: Stack overflow when trying to use regex in java
body: <p>I have read up on some articles on how to optimize regex but none of the answers (less groups, using {X,Y} instead of *) seemed to stop my regex from getting a stack overflow error. </p>
  
  <p>I am trying to make a dynamic search through a file. Lets say i am searching for 'i bet you cannot find me' in a file that is pretty large (2-4 mb). My regex generator would generate the regex: </p>
  
  <pre><code>i(?:.|\s)*?bet(?:.|\s)*?you(?:.|\s)*?cannot(?:.|\s)*?find(?:.|\s)*?me
  </code></pre>
  
  <p>the idea to this regex is that it finds the exact phrase no matter what characters or white space comes between the words. However when i try to use:</p>
  
  <pre><code>Pattern p = Pattern.compile(generatedRegex, Pattern.MULTILINE);
  Matcher m = p.matcher(fileContentsAsString);
  while (m.find()) {
  System.out.println(m.group())
  }
  </code></pre>
  
  <p>I am getting a stack overflow error. I know that regex use recursion but it doesnt seem like this is that bad of a regex. Is there any way I can optimize this regex? Thanks!</p>
  
  <p>ANSWER: </p>
  
  <pre><code>Pattern p = Pattern.compile("i(?:.*)bet(?:.*)you(?:.*)cannot(?:.*)find(?:.*?)me", Pattern.DOTALL);
  </code></pre>
  
  <p>is the pattern/regex that I ultimately am using. Seems fast and no longer getting a stack overflow exception</p>