如何匹配字符串中的日期

How to match date in string

我正试图从一段文本中梳理出一个日期。据我所知,日期看起来总是类似于 Mar 5, 2015(三个字母的月份,没有前导零的日期,四位数的年份)。

不过,文本块的变化更大一些。在大多数情况下,它通常看起来像这样:

We understand that sometimes your travel plans change. We do not charge a change or cancel fee. However, this property (Hotel Name) imposes the following penalty to its customers that we are required to pass on: Cancellations or changes made after 11:59 AM ((GMT-05:00) Eastern Time (US & Canada)) on Mar 10, 2015 are subject to a 1 Night Room & Tax penalty. The property makes no refunds for no shows or early checkouts.

这是我的尝试(val 是包含字符串的变量):

var valDate = val.match("\\\)\\\) on (.*)are");
return valDate[1];

如您所见,我选择了时区末尾的两个 ))(我相信它会一直存在,不管 EST/PST/etc)和紧随其后的 'are'日期。

这非常有效……直到我的一家酒店通过了以下测试:

We understand that sometimes your travel plans change. We do not charge a change or cancel fee. However, this property (Hotel Name) imposes the following penalty to its customers that we are required to pass on: cancellations or changes made before 6:00 PM ((GMT-05:00) Eastern Time (US & Canada)) on Mar 15, 2015 are subject to a 1 Night Room & Tax penalty. Cancellations or changes made after 6:00 PM ((GMT-05:00) Eastern Time (US & Canada)) on Mar 15, 2015 are subject to a 1 Night Room & Tax penalty. The property makes no refunds for no shows or early checkouts.

我的代码 returned:

Mar 15, 2015 are subject to a 1 Night Room & Tax penalty. Cancellations or changes made after 6:00 PM ((GMT-05:00) Eastern Time (US & Canada)) on Mar 15, 2015

这是不尽如人意的地方。我想我明白为什么会这样,但尽管我可能不会修复它,但请尝试。此外,我原来的 match 确实很笨拙(因此出现了这个问题)。我猜可能有更好的方法来梳理日期...我只是不知道如何。

有人可以帮助我吗?我将永远感激不已!

符合您描述的模式是:

(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+([0-9]|[1-2][0-9]|3[0-1]),\s+\d{4}

Regex101 demo

虽然我相信如果你想捕捉日期,你最好找一个图书馆来做这件事。这样的库可能不太容易出错,会有不同的日期模式,并且可能更容易定制。

您可以像 this answer 显示的那样捕获组:

var r = /(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+([0-9]|[1-2][0-9]|3[0-1]),\s+\d{4}/g;
var t = "We understand that sometimes your travel plans change. We do not charge a change or cancel fee. However, this property (Hotel Name) imposes the following penalty to its customers that we are required to pass on: Cancellations or changes made after 11:59 AM ((GMT-05:00) Eastern Time (US & Canada)) on Mar 10, 2015 are subject to a 1 Night Room & Tax penalty. The property makes no refunds for no shows or early checkouts.";
m = r.exec(t);
while (m != null) {
    //do something with m[0]
    alert(m[0]);//example
    m = r.exec(t);
}

JSFiddle.