javascript - 查找文本中的日期

标签 javascript regex node.js text-mining

我想在文档中查找日期。

并以数组形式返回此日期。

假设我有以下文本:

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 对象。

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

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

最佳答案

您可以使用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;
<input id="out">

Regular expression visualization

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

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">

Regular expression visualization

关于javascript - 查找文本中的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32949649/

相关文章:

javascript - 在绘制矩形之前更改 lineCap 和 lineJoin 没有任何作用?

c# - 正则表达式允许一组重复不同时间的字符

javascript - Nodejs 处理错误

javascript - 如何在 chrome 扩展中动态运行后台脚本?

javascript - 如何发送输入文本值

javascript - 如何在 arraybuffer 中存储 32 位整数?

ruby - Ruby lookbehind 断言 (1.9/2.0) 中是否存在错误?

regex - 我可以匹配任意长度字符串中另一个字符正下方的字符吗?

javascript - 在node js中像全局变量一样访问回调之外的变量

javascript - iTunes Search Api 问题 - 未捕获( promise )SyntaxError : Unexpected end of input