2

I have a WordPress site, and am using AJAX to update the archive rather than page reloads (in very basic terms).

So I can either be passing:

http://mysite.com/events/2012/10/17
http://mysite.com/events/2012/10
http://mysite.com/events/2012

I am looking for a JS/jQuery regex method that will retrieve any of these. So far I have the following:

var linkUrl = 'http://mysite.com/events/2012/10';
var linkDate = linkUrl.match(/\d{4}(\/\d{2})+/);
console.log( linkDate ); // output - ["2012/10", "/10", index: 8, input: "/events/2012/10"] 

It appears that it's finding 2 matches, the second of which is not what I want. I'm sure it's a simple thing in my regex.

4

3 回答 3

2

我会试试这个正则表达式/(\d{4})(?:\/(\d{2}))?(?:\/(\d{2}))?$/

'http://mysite.com/events/2012'.match(/(\d{4})(?:\/(\d{2}))?(?:\/(\d{2}))?$/)
// => ["2012", "2012", undefined, undefined]

'http://mysite.com/events/2012/03'.match(/(\d{4})(?:\/(\d{2}))?(?:\/(\d{2}))?$/)
// => ["2012/03", "2012", "03", undefined]

'http://mysite.com/events/2012/03/21'.match(/(\d{4})(?:\/(\d{2}))?(?:\/(\d{2}))?$/)
// => ["2012/03/21", "2012", "03", "21"]
于 2013-06-26T13:33:24.223 回答
0

所以我在我可爱的 ​​O'Reilly 正则表达式书中找到了解决方案。

再次查看我的正则表达式后,我意识到月份[和日期] 表达式被括号括起来,这显然意味着捕获子模式。解决方案是这样的。

var linkUrl = "/events/2012/10/25";
var linkDate = linkUrl.match(/\d{4}(?:\/\d{2})*/);
// output - ["2012/10/25", index: 8, input: "/events/2012/10/25"] 

?:在括号内添加了,它告诉match不捕获子字符串。现在我收到2012/10/17或收到2012/10,具体取决于 URL。

还要注意由于正确排除了子模式而返回的单个值。

于 2013-06-26T13:30:13.080 回答
0

尝试这个。

(?<=/)[0-9]{4}(/[0-9]{1,2})?(/[0-9]{1,2})?
于 2013-06-26T13:35:34.953 回答