title: REGEX in R: extracting words from a string
body: <p>i guess this is a common problem, and i found quite a lot of webpages, including some from SO, but i failed to understand how to implement it.</p>
  
  <p>I am new to REGEX, and I'd like to use it in R to extract the first few words from a sentence.</p>
  
  <p>for example, if my sentence is</p>
  
  <pre><code>z = "I love stack overflow it is such a cool site"
  </code></pre>
  
  <p>id like to have my output as being (if i need the first four words)</p>
  
  <pre><code>[1] "I love stack overflow"
  </code></pre>
  
  <p>or (if i need the last four words)</p>
  
  <pre><code>[1] "such a cool site"
  </code></pre>
  
  <p>of course, the following works</p>
  
  <pre><code>paste(strsplit(z," ")[[1]][1:4],collapse=" ")
  paste(strsplit(z," ")[[1]][7:10],collapse=" ")
  </code></pre>
  
  <p>but i'd like to try a regex solution for performance issues as i need to deal with very huge files (and also for the sake of knowing about it)</p>
  
  <p>I looked at several links, including
  <a href="https://stackoverflow.com/questions/21345973/regex-to-extract-first-3-words-from-a-string">Regex to extract first 3 words from a string</a> and
  <a href="http://osherove.com/blog/2005/1/7/using-regex-to-return-the-first-n-words-in-a-string.html" rel="nofollow noreferrer">http://osherove.com/blog/2005/1/7/using-regex-to-return-the-first-n-words-in-a-string.html</a></p>
  
  <p>so i tried things like </p>
  
  <pre><code>gsub("^((?:\S+\s+){2}\S+).*",z,perl=TRUE)
  Error: '\S' is an unrecognized escape in character string starting ""^((?:\S"
  </code></pre>
  
  <p>i tried other stuff but it usually returned me either the whole string, or the empty string.</p>
  
  <p>another problem with substr is that it returns a list. maybe it looks like the <code>[[]]</code> operator is slowing things a bit (??) when dealing with large files and doing apply stuff.</p>
  
  <p>it looks like the Syntax used in R is somewhat different ?
  thanks !</p>