正则表达式的日期范围 [英] Regular expression for a date range

查看:727
本文介绍了正则表达式的日期范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的目录结构

If I have a directory structure like this

yyyy/dd/mm/<files>

有没有办法在给定的时间范围内使用正则表达式在所有文件中grep字符串?例如,我有一个时间范围:2010/12/25 - 2011/01/01,我需要grep所有文件在相应的日期从12月25日至1月1日

Is there a way to grep for a string in all files in a given time frame using a regex? For example, I have a time frame: 2010/12/25 - 2011/01/01, I need to grep all files in directories corresponding to dates from 25th december to jan 1st

如果我以编程方式执行此操作,是否最好遍历每个yyyy / dd / mm目录中的日期范围和grep文件,而不是使用正则表达式来执行此操作?或者它不会有什么不同?

If I am doing this programmatically, is it better to iterate over the date range and grep files in each yyyy/dd/mm directory than to use a regex to do this? Or would it not make a difference?

推荐答案

在您的情况中,这很简单:

In your case, it's simple enough:

\b(?:2010/12/(?:3[01]|2[5-9])|2011/01/01)\b

将匹配一个包含您指定范围内的日期的字符串。但通常,正则表达式不适合匹配日期范围。它总是一种可能性,但很少是一个好的例子。

will match a string that contains a date in the range you specified. But generally, regexes are not a good fit for matching date ranges. It's always a possibility, but rarely a good one.

例如,在2003/04 / 25-2011 / 04/04范围内,您会得到

For example, for the range 2003/04/25-2011/04/04, you get

\b(?:
2003/04/(?:30|2[5-9])|
2003/(?:(?:0[69]|11)/(?:30|[12][0-9]|0[1-9])|(?:0[578]|1[02])/(?:3[01]|[12][0-9]|0[1-9]))|
2011/04/0[1-4]|2011/(?:02/(?:[12][0-9]|0[1-9])|0[13]/(?:3[01]|[12][0-9]|0[1-9]))|
(?:2010|200[4-9])/(?:02/(?:[12][0-9]|0[1-9])|(?:0[469]|11)/(?:30|[12][0-9]|0[1-9])|(?:0[13578]|1[02])/(?:3[01]|[12][0-9]|0[1-9]))
)\b

如果我必须做这样的事情(并且不能在文件属性中使用创建日期),那么如果是正则表达式,我会使用RegexMagic(创建日期范围正则表达式)和PowerGREP(执行刷新)一次性工作,但这些只能在Windows上使用。如果我不得不经常这样做,我会编写一个小Python脚本来遍历我的目录树,解析每个目录的日期,检查它是否在范围内,然后查看该目录中的文件。

If I had to do something like this (and couldn't use the creation dates in the file attributes), I would either use RegexMagic (to create the date range regex) and PowerGREP (to do the grepping) if it's a one-time job, but these are only available on Windows. If I had to do this more often, I'd write a small Python script that walks through my directory tree, parses the date for each directory, checks if it's in range, and then looks at the files in that directory.

这篇关于正则表达式的日期范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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