Find dates in text [duplicate]

丶灬走出姿态 提交于 2019-12-25 02:59:32

问题


I want to find Dates in a document.

And return this Dates in an array.

Lets suppose I have this text:

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

Now my code should return ['03/09/2015','27-03-1994'] or simply two Date objects in an array.

My idea was to solve this problem with regex, but the method search() only returns one result and with test() I only can test a string!

How would you try to solve it? Espacially when you dont know the exact format of the Date? Thanks


回答1:


You can use match() with regex /\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;
<input id="out">

Or you can do something like this with help of capturing group

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;
<input id="out">



来源:https://stackoverflow.com/questions/32949649/find-dates-in-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!