Negative look-ahead assertion in list.files in R

♀尐吖头ヾ 提交于 2020-01-01 04:57:09

问题


I try to list all files in a directory that do not start with "Camera1", but end with ".png". For doing so, I am using a regular expression in list.files in R. To exclude "Camera1", I tried to use a negative lookahead, 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 :)


回答1:


Looks like the default engine doesn't like lookarounds, so you need to use Perl. This 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 doesn't:

grep("^(?!Camera1).*\\.png", dat, value=T)
# invalid regular expression '(?<!Camera1)\.png', reason 'Invalid regexp'

So, to do what you what you want:

grep("(?<!Camera1)\\.png", list.files(), perl=T, value=T)


来源:https://stackoverflow.com/questions/30535960/negative-look-ahead-assertion-in-list-files-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!