【问题标题】:grep to match a certain number sequence in a mix of text and numbersgrep 匹配文本和数字混合中的某个数字序列
【发布时间】:2015-10-23 15:44:30
【问题描述】:

我有几个类似于“PRISM_ppt_stable_4kmM2_------_bil.bil”的文件,其中 ------ 是年和月,如 190112。文件日期范围从 189501 到 198012。在 R 中,在 Windows 7 机器上,我想匹配从 192001 到 193912 的所有文件。我很确定我想要grepl(),但我不知道如何在命令中引用序列.我试过了

my.files[grepl('PRISM.*/1920/.bil$',my.files)]

my.files[grepl('PRISM.*[1][9][2][0].',my.files)]

和其他变体,但只会收到错误消息。我知道 [0-9]{4} 将匹配任何四个数字序列,但这将匹配所有文件。

【问题讨论】:

  • (189[5-9]|1[9]([0-7][0-9]|80))(0[1-9]|1[0-2]) 试试这个正则表达式。
  • @AruneshSingh 感谢您的建议。这将涵盖所有文件/日期。我正在寻找一组较小的日期,但我能够使用您的回复找到我想要的。 my.files[grepl('(192[0-9]|193[0-9])(0[1-9]|1[0-2])',my.files)]
  • 大声笑,对不起,我以为你想从 1895 匹配到 1980,因为它确实是正确的。

标签: regex r grepl


【解决方案1】:

这是我要做的:

# Reproducible example of file list
library(stringr)
ym <- paste0(1895:1980, str_pad(1:12, 2, pad='0'))
file_list <- paste0("PRISM_ppt_stable_4kmM2_", ym, "_bil.bil")

# Create a list of desired dates and convert to your date format
dates <- seq(as.Date('1920-01-01'), as.Date('1939-12-01'), by='month')
dates <- format(dates, '%Y%m')

# Subset the file list
your_files <- file_list[str_extract(file_list, '[0-9]{6}') %in% dates]

【讨论】:

  • 要签出的新包。我没有想到使用日期。日期对象仍然给我带来问题。
猜你喜欢
  • 1970-01-01
  • 2016-05-20
  • 1970-01-01
  • 2021-04-28
  • 2023-04-06
  • 1970-01-01
  • 2011-10-12
  • 2012-05-11
  • 2022-10-15
相关资源
最近更新 更多