How to extract the last 4 digits of a string of characters in R
<p>I would like to extract the LAST 4 digits in a given string, but can't figure it out.  The LAST 4 digits could be "XXXX" or "XXXX-". Ultimately, I have a list of heterogeneous entries that include single years (i.e., 2001- or 2001), lists of years (i.e., 2001, 2004-), range of years (i.e., 2001-2010), or a combination of these with or without a dash ("-") at the end of the entry.</p>

<p>I realize that '$' is the token to identify the END, and '^' is used to identify the START in regular expressions. I'm able to extract the FIRST 4 easily. Here is an example of what I'm able to do and the code that is not working for the LAST 4 digits: </p>

<pre><code>library(stringr)
test &lt;- c("2009-", "2008-2015", "2001-, 2003-2010, 2012-")
str_extract_all(test, "^[[:digit:]]{4}") # Extracts FIRST 4
</code></pre>

<blockquote>
  <p>[[1]]</p>
  
  <p>[1] "2009"  "2008"  "2001"</p>
</blockquote>

<pre><code>str_extract_all(test, "[[:digit:]]{4}$") # Does not extract LAST 4
</code></pre>

<blockquote>
  <p>[[1]]</p>
  
  <p>character(0)</p>
  
  <p>[[2]]</p>
  
  <p>"2015"</p>
  
  <p>[[3]]</p>
  
  <p>character(0)</p>
</blockquote>

<pre><code>str_extract_all(test, "\\d{4}$")
</code></pre>

<blockquote>
  <p>[[1]]</p>
  
  <p>character(0)</p>
  
  <p>[[2]]</p>
  
  <p>"2015"</p>
  
  <p>[[3]]</p>
  
  <p>character(0)</p>
</blockquote>

<p>The result I desire is:</p>

<blockquote>
  <p>[1] "2009"  "2015"  "2012"    </p>
</blockquote>