【问题标题】:Extracting dates in different formats from different strings in JavaScript从 JavaScript 中的不同字符串中提取不同格式的日期
【发布时间】:2016-07-10 22:01:57
【问题描述】:

我正在编写一个 node.JS 应用程序来解析来自谷歌照片的谷歌外卖数据,用于 EXIF 数据。

我不擅长正则表达式,并且尝试过 regexr.com 等网站无济于事,因为有很多未知数。但是我想知道是否有更有效的方法来做到这一点?

假设我可以有各种潜在的字符串

"IMG_20150628_184721-ANIMATION" # There is a date + time within, but they are not in an ISO format, also non-regular characters "Screenshot_2015-06-27-22-51-00" # Has a date/time at the end, but also has useless string within it "2015-06-28" # Cleanly formatted date without time "2015-06-28 22:51:05" # Cleanly formatted date and time "2015-06-28 #1" # Date + Space and Extra characters that I don't want "2015-06-28 #3 " # Date + Space and extra characters that I don't want and a trailing space "2015-06-18-19" # Date + An extra number (happens to be the next day) "NoDateOrTimeInThisString" # No Date "IMG_1234" # No date

此列表并非详尽无遗,日期之前+之后可能还有其他字符串。日期/时间也可能实际上不在字符串中

我无法知道最终会使用哪些特定文件名,并且在我的知识范围内,我不知道如何从每个文件名中提取日期。

有没有人知道我将如何在 JavaScript 中执行此操作?例如库?如果可能的话,我希望能够将其放入 JS 日期/时间对象中。但我不知道该怎么做。

【问题讨论】:

标签: javascript regex date datetime time


【解决方案1】:

您可能想看看Moment.js

此外,正则表达式本身值得一整套教程,它们是自己的语言。具体来说,看看捕获组,它允许您提取匹配表达式的某些部分。

您可以对输入做出哪些假设?会不会总有一个序列 yyyy(...)mm(...)dd 隐藏在某个地方?

你可以试试

.*([0-9]{4}).*([0-9]{2}).*([0-9]{2}).*

(还没试过这个表达式,可能需要一些调整。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多