title: Efficient Regular Expression for big data, if a String contains a word
body: <p>I have a code that works but is extremely slow. This code determines whether a string contains a keyword. The requirements I have need to be efficient for hundreds of keywords that I will search for in thousands of documents.</p>
  
  <p>What can I do to make finding the keywords (without falsely returning a word that contains the keyword) efficiently?</p>
  
  <p>For example:</p>
  
  <pre><code>String keyword="ac"; 
  String document"..."  //few page long file
  </code></pre>
  
  <p>If i use : </p>
  
  <pre><code>if(document.contains(keyword) ){
  //do something
  }
  </code></pre>
  
  <p>It will also return true if document contains a word like "account";</p>
  
  <p>so I tried to use regular expression as follows:</p>
  
  <pre><code>String pattern = "(.*)([^A-Za-z]"+ keyword +"[^A-Za-z])(.*)";
  Pattern r = Pattern.compile(pattern);
  Matcher m = r.matcher(document);
  if(m.find()){
     //do something
  }
  </code></pre>
  
  <p>Summary:</p>
  
  <p>This is the summary: Hopefully it will be useful to some one else:</p>
  
  <ol>
  <li>My regular expression would work but extremely impractical while
  working with big data.  (it didn't terminate)</li>
  <li>@anubhava perfected the regular expression.  it was easy to
  understand and implement. It managed to terminate which is a big
  thing. but it was still a bit slow. (Roughly about 240 seconds)</li>
  <li>@Tomalak solution is abit complex to implement and understand but it
  was the fastest solution. so hats off mate.(18 seconds)</li>
  </ol>
  
  <p>so @Tomalak solution was ~15 times faster than @anubhava. </p>