R 中的 list.files 模式参数,扩展正则表达式使用 [英] list.files pattern argument in R, extended regular expression use

查看:151
本文介绍了R 中的 list.files 模式参数,扩展正则表达式使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我跑

  dir.create('./junk_data')
  file.create(paste('./junk_data/QWE',01:12,01:31,2005:2015,'.3',sep=''))
  file.create(paste('./junk_data/RTY',01:12,01:31,2005:2015,'.3',sep=''))

并且想要列出所有以QWE开始2011.3结束的文件.我试过了

and want to list all the files that begin with QWE and end with 2011.3. I tried

list.files('./junk_data/',pattern='QWE....2011.3',full.names=T)

list.files('./junk_data/',pattern='QWE....2011.3',full.names=T,perl=T)

但我猜 '.' 并不代表我的想法,因为我没有得到我想要的文件.

but I guess '.' doesn't mean one what I think, as I get none of the files I want.

我尝试了一些关于正则表达式的教程,但没有任何乐趣.

I tried a few tutorials on regex, but no joy.

推荐答案

正如 Arun 在他的例子中所展示的,一个点通常意味着匹配任何字符",所以要匹配一个点,你需要将它转义:\\..您可以使用 glob2rx,它使用 * 作为通配符并匹配其他字符,就好像它们是固定的一样.

As Arun showed in his example, a dot usually means "match any character", so to match a dot you need to escape it: \\.. You can create the pattern most easily with glob2rx, which uses * as a wildcard and matches other characters as though they are fixed.

glob2rx("QWE*2011.3")   #"^QWE.*2011\\.3$"
list.files("./junk_data/", pattern = glob2rx("QWE*2011.3"), full.names = TRUE)

这篇关于R 中的 list.files 模式参数,扩展正则表达式使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆