title: Regular expression for counting words in a sentence
body: <pre><code>public static int getWordCount(String sentence) {
      return sentence.split("(([a-zA-Z0-9]([-][_])*[a-zA-Z0-9])+)", -1).length
           + sentence.replaceAll("([[a-z][A-Z][0-9][\\W][-][_]]*)", "").length() - 1;
  }
  </code></pre>
  
  <p>My intention is to count the number of words in a sentence. The input to this function is the the lengthy sentence. It may have 255 words. </p>
  
  <ol>
  <li>The word should take hyphens or underscores in between</li>
  <li>Function should only count valid words means special character should not be counted eg. &amp;&amp;&amp;&amp; or #### should not count as a word.</li>
  </ol>
  
  <p>The above regular expression is working fine, but when hyphen or underscore comes in between the word eg: co-operation, the count returning as 2, it should be 1. Can anyone please help?</p>