Search code examples
regexrstringrmagrittr

Match period with Regex in R


A trivial regex operation in R, but even the other questions on SO which appear relevant aren't helping me

I have a list of csv files names--

library(plyr)
library(stringr)
library(magrittr)


set.seed("43212")

foo <- c(raply(3, 
          sample(letters, 3, T) %>% 
            paste0(collapse = "")),
         raply(3, 
          sample(0:9, 3, T) %>% 
            paste0(collapse = ""))) %>% 
         str_c(".csv") 

foo
[1] "hoo.csv" "wwc.csv" "lll.csv" "406.csv" "120.csv" "362.csv"

I want to extract the .csv files whose name end with some number, and exclude the filenames which end with a character.

I thought I understood regex and escaped characters in R--but this:

foo %>% 
  extract(str_sub(., -5) == "\\d\\.csv")

fails--what am I missing?


Solution

  • You may use grep.

    grep("\\d\\.csv$", x, value=T)
    

    or

    grep("[[:digit:]]\\.csv$", x, value=T)