在 R 函数的 list.files 中使用正则表达式

kel*_*rog 3 regex r

我想使用 R 的 list.files 列出包含此模式“un[数字]”的文件,例如 filename_un1.txt、filename_un2.txt 等...这是一般代码:

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

我尝试un\d过输入模式但不起作用。

Wik*_*żew 7

您应该记住,在 R 中,字符串允许使用转义序列。但是,正则表达式引擎需要一个文字\来传递速记字符类(例如\d数字)或转义特殊字符(例如\\.匹配文字点)。

所以,你需要

pattern = "_un\\d+\\.txt$"
Run Code Online (Sandbox Code Playgroud)

在哪里

  • _un- 匹配文字子字符串_un
  • \\d+- 匹配 1 个或多个数字(与+一个或多个量词一样)
  • \\.- 匹配文字点
  • txt- 匹配字符的字面序列txt
  • $- 字符串末尾。