title: Regex to extract Noun Phrases from a Part of Speech parse tree?
body: <p>I am trying to extract all three word noun phrases from a Stanford POS Parse Tree. Basically, anything that looks like:</p>
  
  
  
  <pre class="lang-none prettyprint-override"><code>(NP (TAG WORD) (TAG WORD) (TAG WORD))
  </code></pre>
  
  <p>Or:</p>
  
  <pre class="lang-none prettyprint-override"><code>(NP (TAG WORD) (TAG (TAG WORD) (TAG WORD)))
  </code></pre>
  
  <p>This is what a parse tree can look like:</p>
  
  <pre class="lang-none prettyprint-override"><code>(ROOT (SQ (VBZ Is) (NP (DT this)) (NP (DT an) (NN asthma) (NN attack)) (. ?)))
  </code></pre>
  
  <p>When I do this regex, it extracts the correct 3 word noun phrase:</p>
  
  <pre class="lang-ruby prettyprint-override"><code>threeWordNounPhrases = full.scan(/\(NP \([^()]+ [^()]+\) \([^()]+ [^()]+\)\)/)
  # =&gt; "(NP (DT an) (NN asthma) (NN attack))"
  </code></pre>
  
  <p>However, this does not work for something like:</p>
  
  <pre class="lang-none prettyprint-override"><code>(ROOT (SQ (NNP Should) (NP (PRP I)) (VP (VB watch) (NP (NP (NNP Game)) (PP (IN of) (NP (NNP Thrones)))) ) (. ?)))
  </code></pre>
  
  <p>Which should return:</p>
  
  <pre class="lang-none prettyprint-override"><code>(NP (NP (NNP Game)) (PP (IN of) (NP (NNP Thrones))))
  </code></pre>