title: Java Counting # of occurrences of a word in a string
body: <p>I have a large text file I am reading from and I need to find out how many times some words come up.  For example, the word <code>the</code>.  I'm doing this line by line each line is a string.</p>
  
  <p>I need to make sure that I only count legit <code>the</code>'s--the <code>the</code> in <code>other</code> would not count.  This means I know I need to use regular expressions in some way.  What I was trying so far is this:  </p>
  
  <pre><code>numSpace += line.split("[^a-z]the[^a-z]").length;  
  </code></pre>
  
  <p>I realize the regular expression may not be correct at the moment but I tried without that and just tried to find occurrences of the word <code>the</code> and I get wrong numbers too.  I was under the impression this would split the string up into an array and how many times that array was split up was how many times the word is in the string.  Any ideas I would be grateful.</p>
  
  <p>Update:
  Given some ideas, I've come up with this:  </p>
  
  <pre><code>numThe += line.split("[^a-zA-Z][Tt]he[^a-zA-Z]", -1).length - 1;
  </code></pre>
  
  <p>Though still getting some strange numbers.  I was able to get an accurate general count (without the regular expression), now my issue is with the regexp.  </p>