我的日期正则表达式有什么问题? [英] What is wrong with my date regex?

查看:123
本文介绍了我的日期正则表达式有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var dateRegex = /\/Date\((\d+)\)\//g;    // [0-9] instead of \d does not help.
dateRegex.test("/Date(1286443710000)/"); // true
dateRegex.test("/Date(1286445750000)/"); // false

Chrome和Firefox JavaScript控制台都会确认。他们是什么人?

Both Chrome and Firefox JavaScript consoles confirm. What the hell, guys?

编辑:更简单的测试用例:

even simpler test case:

var dateRegex = /Date\(([0-9]+)\)/g;
dateRegex.test("Date(1286445750000)"); // true
dateRegex.test("Date(1286445750000)"); // false
dateRegex.test("Date(1286445750000)"); // true
dateRegex.test("Date(1286445750000)"); // false
dateRegex.test("Date(1286445750000)"); // true

这表明它每次都会替换true / false ...

This shows that it alternates true/false every time...

推荐答案

在你的情况下,从最后删除 g 修饰符,例如:

In your case remove the g modifier from the end, for example:

var dateRegex = /\/Date\((\d+)\)\//;
dateRegex.test("Date(1286445750000)"); // true
dateRegex.test("Date(1286445750000)"); // true
dateRegex.test("Date(1286445750000)"); // true
dateRegex.test("Date(1286445750000)"); // true
dateRegex.test("Date(1286445750000)"); // true

这是一个在ECMAScript 3中实现正则表达式的错误,这里有一个很棒的帖子

It's a bug with the way regexes are implemented in ECMAScript 3, there's a great post on the details here.

这篇关于我的日期正则表达式有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆