Search code examples
rregexstringsplitstringi

Extracting strings from links using regex in R


I have a list of url links and i want to extract one of the strings and save them in another variable. The sample data is below:

  sample<-  c("http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr01f2009.pdf",
            "http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr02f2001.pdf",
           "http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr03f2002.pdf",
          "http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr04f2004.pdf",
         "http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr05f2005.pdf",
           "http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr06f2018.pdf",
           "http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr07f2016.pdf",
            "http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr08f2015.pdf",
          "http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr09f2020.pdf",
             "http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr10f2014.pdf")

sample

 [1] "http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr01f2009.pdf"
 [2] "http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr02f2001.pdf"
 [3] "http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr03f2002.pdf"
 [4] "http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr04f2004.pdf"
 [5] "http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr05f2005.pdf"
 [6] "http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr06f2018.pdf"
 [7] "http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr07f2016.pdf"
 [8] "http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr08f2015.pdf"
 [9] "http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr09f2020.pdf"
[10] "http://dps.endavadigital.net/owgr/doc/content/archive/2009/owgr10f2014.pdf"

I want to extract week and year using regex.

     week year
1     1 2009
2     2 2001
3     3 2002
4     4 2004
5     5 2005
6     6 2018
7     7 2016
8     8 2015
9     9 2020
10   10 2014

Solution

  • You could use str_match to capture numbers after 'owgr' and 'f' :

    library(stringr)
    str_match(sample, 'owgr(\\d+)f(\\d+)')[, -1]
    

    You can convert this to dataframe, change class to numeric and assign column names.

    setNames(type.convert(data.frame(
              str_match(sample, 'owgr(\\d+)f(\\d+)')[, -1])), c('year', 'week'))
    
    #   year week
    #1     1 2009
    #2     2 2001
    #3     3 2002
    #4     4 2004
    #5     5 2005
    #6     6 2018
    #7     7 2016
    #8     8 2015
    #9     9 2020
    #10   10 2014
    

    Another way could be to extract all the numbers from last part of sample. We can get the last part with basename.

    str_extract_all(basename(sample), '\\d+', simplify = TRUE)