在文本中查找日期 [英] Find dates in text
问题描述
我想在文档中查找日期.
I want to find Dates in a document.
并在数组中返回此日期.
And return this Dates in an array.
假设我有这段文字:
On the 03/09/2015 I am swiming in a pool, that was build on the 27-03-1994
现在我的代码应该返回 ['03/09/2015','27-03-1994']
或者只是数组中的两个 Date 对象.
Now my code should return ['03/09/2015','27-03-1994']
or simply two Date objects in an array.
我的想法是用正则表达式解决这个问题,但是方法 search()
只返回一个结果,而使用 test()
我只能测试一个字符串!
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
推荐答案
您可以使用 match()
与正则表达式 /\d{2}([\/.-])\d{2}\1\d{4}/g
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">
这篇关于在文本中查找日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!