正则表达式 - 从文件列表中的文件名中提取日期

Regex - Extract date from file name in list of files

我在本地目录中有多个文件,名称如下:

asd-3A-yyyyMMdd

其中 yyyyMMdd 代表日期。 还有一些文件名为:

bcd-3A-yyyyMMdd

还有一堆不同名称的文件,我不需要。 如何从以 asd 开头的文件中仅提取日期? 我尝试的任何方法似乎都不起作用。

解决方案

这个正则表达式

asd-[0-9][a-z]-([0-9]{4})([0-9]{2})([0-9]{2})

将执行以下操作

  • 要求字符串
    • 以字符 asd-
    • 开头
    • 后跟一个数字和一个字母,然后是 -
    • 后跟类似日期的数字。
  • 创建以下捕获组
    • 0 整个匹配的字符串
    • 1 年
    • 2月
    • 3 天

注意:此正则表达式不验证日期是否合法。

例子

另见 Live Demo

给定以下示例文本

bsd-3A-20170523
asd-3A-20170523
NotTheDroidsYourLookingFor-20171131
asd-1D-20170523

Returns以下匹配

Match 1
Full match  16-31   `asd-3A-20170523`
Group 1.    23-27   `2017`
Group 2.    27-29   `05`
Group 3.    29-31   `23`

Match 2
Full match  68-83   `asd-1D-20170523`
Group 1.    75-79   `2017`
Group 2.    79-81   `05`
Group 3.    81-83   `23`

说明

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  asd-                     'asd-'
--------------------------------------------------------------------------------
  [0-9]                    any character of: '0' to '9'
--------------------------------------------------------------------------------
  [a-z]                    any character of: 'a' to 'z'
--------------------------------------------------------------------------------
  -                        '-'
--------------------------------------------------------------------------------
  (                        group and capture to :
--------------------------------------------------------------------------------
    [0-9]{4}                 any character of: '0' to '9' (4 times)
--------------------------------------------------------------------------------
  )                        end of 
--------------------------------------------------------------------------------
  (                        group and capture to :
--------------------------------------------------------------------------------
    [0-9]{2}                 any character of: '0' to '9' (2 times)
--------------------------------------------------------------------------------
  )                        end of 
--------------------------------------------------------------------------------
  (                        group and capture to :
--------------------------------------------------------------------------------
    [0-9]{2}                 any character of: '0' to '9' (2 times)
--------------------------------------------------------------------------------
  )                        end of