kelvinfrog
kelvinfrog

Reputation: 467

using regular expression in list.files of R function

I want to use list.files of R to list files containing this pattern "un[a digit]" such as filename_un1.txt, filename_un2.txt etc... Here is the general code:

list_files <- list.files(path="my_file_path", recursive = TRUE, pattern = "here I need help", full.names = TRUE)

I have tried putting un\d in the pattern input but does not work.

Upvotes: 3

Views: 4187

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627292

You should bear in mind that in R, strings allow using escape sequences. However, the regex engine needs a literal \ to pass shorthand character classes (like \d for digits) or to escape special chars (like \\. to match a literal dot.)

So, you need

pattern = "_un\\d+\\.txt$"

where

  • _un - matches a literal substring _un
  • \\d+ - matches 1 or more digits (as + is a one or more quantifier)
  • \\. - matches a literal dot
  • txt - matches a literal sequence of characters txt
  • $ - end of string.

Upvotes: 7

jkt
jkt

Reputation: 946

list_files <- list.files(path="my_file_path", recursive = TRUE, pattern = "un[0-9]", full.names = TRUE)

Upvotes: 1

Related Questions