python - 如何将与正则表达式匹配的所有字符串放入 Python 列表中?

标签 python regex list date

因此,在我的 Python 脚本中,我打开一个文本文件,其中包含格式为“1991 年 1 月 26 日”的日期

这是我的正则表达式:

pattern = """
(?:(September|April|June|November),\ (0?[1-9]|[12]\d|30),\ ((?:19|20)\d\d))#Months   with 30 days
|(?:(January|March|May|July|August|October|December),\ (0?[1-9]|[12]\d|3[01]),\ ((?:19|20)\d\d))#Months with 31 days
|(?:February, (?:(?:(0?[1-9]|1\d|2[0-8]),\ ((?:19|20)\d\d))|(?:(29),\ ((?:(?:19|20)(?:04|08|12|16|20|24|28|32|36|40|44|48|52|56|60|64|68|72|76|80|84|88|92|96))|2000))))#February with 28 days or 29 with a leap year
"""

r = re.compile(pattern, re.VERBOSE)

此正则表达式应匹配任何实际日期,包括闰年的 2 月 29 日。

我遇到的问题是找出一种方法来浏览我打开的文本文件并将所有匹配的日期放入列表中。我尝试过使用 .match、.search、.split 和其他的,但我没有任何运气。有没有办法将所有匹配项作为字符串放入列表中,以便我可以轻松地将列表与另一个列表进行比较并找到两个列表中的所有日期?基本上我想要一个看起来像这样的列表

[“1990年1月1日”、“2012年2月29日”、“1945年12月25日”,....]

另外,请告诉我我的正则表达式是否正确。我根据另一个问题的答案修改了它,但我不确定我是否正确,因为我无法查看文本文件中的日期是否匹配。

最佳答案

你没有提到 re.findall() 在您尝试过的事情列表中。这将为您提供所有正则表达式匹配的列表。

但是,您需要使用所有非捕获组 (?:...) ,或者您将获得所有匹配组的列表 (...) 。因此,我建议

pattern = """
    (?:September|April|June|November)
    ,[ ] 
    (?:0?[1-9]|[12]\d|30)
    ,[ ]
    (?:19|20)\d\d # Months with 30 days

    |

    (?:January|March|May|July|August|October|December)
    ,[ ] 
    (?:0?[1-9]|[12]\d|3[01])
    ,[ ] 
    (?:19|20)\d\d # Months with 31 days

    |

    February
    ,[ ] 
    (?:
     (?:0?[1-9]|1\d|2[0-8])
     ,[ ] 
     (?:19|20)\d\d
    |
     29
     ,[ ] 
     (?:
      (?:19|20)
      (?:04|08|12|16|20|24|28|32|36|40|44|48|
         52|56|60|64|68|72|76|80|84|88|92|96)
     |
      2000
     )
    ) # February with 28 days or 29 with a leap year"""

但是您真的需要验证日期的正确性吗?您是否期待像 February, 31, 2000 这样的虚假日期出现在您的数据中?如果没有,您可以极大地简化您的正则表达式。或者至少将日期验证委托(delegate)给日期解析函数,该函数比可怕的正则表达式更适合此任务。

例如:

pattern = """
    (?:January|February|March|April|May|June|
       July|August|September|October|November|December)
    ,[ ]
    [0-3]?\d
    ,[ ]
    (?:19|20)\d\d
"""

匹配像January, 0, 1999这样的废话或February, 31, 2000 ,但这真的很重要吗?

关于python - 如何将与正则表达式匹配的所有字符串放入 Python 列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10310023/

相关文章:

java - 如何使用正则表达式在 TreeSet<String> 的范围内查找单词 (java)

mysql - 如何用 REGEX 替换列中的字符串

r - 使用 dplyr group_by : return a list of data frames 模拟 split()

python - 尝试将日期列表放入 date.year、date.month、date.day 中进行比较?

python - 在 Python 中解析 Elasticsearch json 输出

python - 使用 tsfresh 中的 extract_(relevant_)features 时出现(类型转换)错误

javascript - 解析单个用户输入字符串以获取高级搜索条件

python - 生成 Twitter 的共享消息和缩短的 URL

python - 应用程序引擎 NeedIndexError : no matching index found

python - 在 1 和 0 的巨大列表中提取 1 密集区域的边界