在文字中查找日期

Joh*_*ith 0 javascript regex text-mining node.js

我想在文档中找到日期。

并以数组形式返回此Date。

假设我有这段文字:

On the 03/09/2015 I am swiming in a pool, that was build on the 27-03-1994
Run Code Online (Sandbox Code Playgroud)

现在我的代码应该返回['03/09/2015','27-03-1994']一个数组中的两个Date对象。

我的想法是使用正则表达式解决此问题,但该方法search()仅返回一个结果,并且test()只能测试字符串!

您将如何解决?特别是当您不知道日期的确切格式时?谢谢

Pra*_*lan 5

您可以使用match()正则表达式/\d{2}([\/.-])\d{2}\1\d{4}/g

var str = 'On the 03/09/2015 I am swiming in a pool, that was build on the 27-03-1994';

var res = str.match(/\d{2}([\/.-])\d{2}\1\d{4}/g);

document.getElementById('out').value = res;
Run Code Online (Sandbox Code Playgroud)
<input id="out">
Run Code Online (Sandbox Code Playgroud)

正则表达式可视化

或者,您可以在捕获小组的帮助下执行类似的操作

var str = 'On the 03/09/2015 I am swiming in a pool, that was build on the 27-03-1994';

var res = str.match(/\d{2}(\D)\d{2}\1\d{4}/g);

document.getElementById('out').value = res;
Run Code Online (Sandbox Code Playgroud)
<input id="out">
Run Code Online (Sandbox Code Playgroud)

正则表达式可视化

  • 像`/ \ d {1,2} \ D \ d {1,2} \ D(\ d {2} | \ d {4})/ g之类的东西似乎更合适,但9月3日这样的日期呢? ,2015年*? (2认同)
  • @JohnSmith-\ D与任何非数字匹配。也许范围太广,您可以改用`[-。\ /]`。 (2认同)
  • @JohnSmith-交换2和4:`/ \ d {1,2} \ D \ d {1,2} \ D(\ d {4} | \ d {2})/ g`。 (2认同)