Negative assertion on lists in R
I am trying to list all the files in a directory that don't start with "Camera1" but end with ".png". To do this, I use a regex in list.files in R. To exclude "Camera1" I tried to use a negative result, but it doesn't work. Where is my mistake?;)
list.files(pathToDirectory, pattern = "^(?!Camera1).*\\.png")
I get the error: invalid 'pattern' regular expression
Thanks in advance.
+3
source to share
1 answer
It looks like the default engine doesn't like search queries, so you need to use Perl. It works:
dat <- c("Camera1.png", "Camera2.png", "hello.png", "boo")
grep("^(?!Camera1).*\\.png", dat, value=T, perl=T)
# [1] "Camera2.png" "hello.png"
But this is not the case:
grep("^(?!Camera1).*\\.png", dat, value=T)
# invalid regular expression '(?<!Camera1)\.png', reason 'Invalid regexp'
So, to do what you want:
grep("(?<!Camera1)\\.png", list.files(), perl=T, value=T)
+3
source to share