2017-05-25 149 views
-1

只匹配一部分,我有串返回字符串

var v = "09/30/2016 12:00am - 2:00am"; 

我需要得到这个字符串的唯一日期部分:"09/30/2016"

对于它,我有正则表达式

var dateFormatRegex = /^(0[1-9]|1[012])\/(0[1-9]|[12][0-9]|3[01])\/(19|20)\d\d$/ig; 

但它只匹配字符串,如果只有日期字符串。

我应该添加到我的正则表达式中以获得来自字符串09/30/2016 12:00am - 2:00am09/30/2016

+3

返回是否必须是正则表达式? 'v.split('')[0]' – cgTag

+0

为了从已知好格式的字符串中获得这个结果,你应该'var datePart = v.substr(0,10);' –

+1

看看['String。匹配函数](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/match) – Lix

回答

1

你快到了!

您唯一的错误是您已将$置于您的正则表达式的末尾,这使得它与您发布的字符串不匹配。

使用String.match将返回匹配组的阵列 - 在这种情况下,你只能有一个,然后你就可以用matches[0]

var dateFormatRegex = /^(0[1-9]|1[012])\/(0[1-9]|[12][0-9]|3[01])\/(19|20)\d\d/ig; 
// removed $ as in the target strings there is still stuff after the date 

var v = "09/30/2016 12:00am - 2:00am"; 
var matches = v.match(dateFormatRegex); 
var date = matches[0]; // === 09/30/2016" 
+0

这是一个单独的问题,所以请为此创建一个新问题 – Aron