【问题标题】:regex to match file names blahblah_200901.csv (yyyymm)正则表达式匹配文件名 blahblah_200901.csv (yyyymm)
【发布时间】:2016-06-18 15:44:10
【问题描述】:

我一直在修改正则表达式来匹配看起来像这样的文件名:

blahblah_200901.csv (2009, January)
blahblah_201512.csv (2015, December)

我有一个传入 from_year、to_year、from_month、to_month 的函数,因此我可以获取范围,但我在使用正确的正则表达式时遇到了困难。月份字段由两位数指定(即 01 到 12)。

import os, re
for f in os.listdir("/path/dir"):
   if re.match(x,f):
   print (f)

上面代码中的 x 有问题。

【问题讨论】:

  • r"blahblah_(19|20)\d{2}(1[0-2]|0[1-9])" 将匹配 20 世纪和 21 世纪任何年份的月份 (01-12)。
  • 如何通过年月输入变量控制正则表达式?我希望能够匹配由年(从,到)和月(从到)变量定义的所有可能性的子集。
  • 我明白了。涵盖日期范围的正则表达式模式将非常复杂。通过解析文件名并比较适当的位,所涉及的 if-else 逻辑将更容易和更干净地解决......

标签: python regex pattern-matching match filenames


【解决方案1】:

最简单的方法是根本不进行任何匹配;相反,您将拥有第一个和最后一个文件名,并看到该值适合 2:

start = 'blahblah_{:04}{:02}'.format(from_year, from_month)
end = 'blahblah_{:04}{:02}'.format(to_year, to_month)

for f in os.listdir('/path/dir'):
    if start <= f <= end:
        print(f)

如果前缀不同,或者正则表达式比较复杂,你可以使用捕获组获取日期部分,然后将它们转换为整数:

m = re.match('blahblah(\d{4})(\d{2})', f)
if m:
    year = int(m.group(1))
    month = int(m.group(2))

    if (from_year, from_month) <= (year, month) <= (to_year, to_month):
        print(f)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    相关资源
    最近更新 更多