简体   繁体   中英

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.

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.
list_files <- list.files(path="my_file_path", recursive = TRUE, pattern = "un[0-9]", full.names = TRUE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM