关于正则表达式:javascript正则表达式解析.net json日期时间

javascript regular expression to parse a .net json Datetime

我不是正则表达式专家,所以我想寻求帮助以得到这样的正则表达式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var regExp = ???

regExp.exec('\/Date(1330848000000-0800)\/') = [..., '1330848000000', '0800']

// optional gmt
regExp.exec('\/Date(1330848000000)\/') = [..., '1330848000000', null]

regExp.exec('\/Date(1)\/') = [..., '1', null]

// gmt required if - is present
regExp.exec('\/Date(1330848000000-)\/') = null

// escaping backslash is required
regExp.exec('/Date(1330848000000-0800)\/') = null
regExp.exec('\/Date(1330848000000-0800)/') = null

// case sensitive
regExp.exec('\/date(1330848000000-0800)\/') = null

// only numbers allowed
regExp.exec('\/Date(1aaa848000000-0800)\/') = null
regExp.exec('\/Date(1330848000000-0a00)\/') = null

我很早就被这样愚蠢的事情缠住了:

1
2
3
/\\bla(.*)bla/.exec('\bla123bla') = null // instead of [ ..., '123']

new RegExp('\\\\bla(.*)bla').exec('\bla123bla') = null // instead of [ ..., '123']


如果字符串中除时间和时区之外从未包含任何其他数字,则可以使用此regex:

1
/(\d+)(?:-(\d+))?/

输入代码:

1
2
var regex = /(\d+)(?:-(\d+))?/;
// regex.exec...

如果确实需要验证并从字符串中提取数字:

1
/^\/Date\((\d+)(?:-(\d+))?\)\/$/

上面的regex将检查字符串是否遵循正确的格式,并提取出数字。


以下regex检查您所需的约束:

1
\\/Date\((\d{13})(-(\d{4}))?\)\\/

它检查\,后面是/,后面是文本Date,后面是包含13位数字的括号,以及可选的-序列,后面是4位数字,然后是所需的\/

\\与单个\匹配,后者需要转义,因为它是regex中的一个特殊字符。在()的情况下也是如此。

从中,$1与括号内的13位数字匹配,$3与4位数字匹配(如果存在)。


我一直在玩正则表达式,最后得到了它

转义斜杠只是被javascript忽略了,所以这个是我提出的解决方案(在chrome控制台上测试)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
var regExp
undefined

regExp = /^\/Date\((\d+)(?:-(\d+))?\)\/$/
/^\/Date\((\d+)(?:-(\d+))?\)\/$/

regExp.exec('\/Date(1330848000000-0800)\/')
["/Date(1330848000000-0800)/","1330848000000","0800"]

regExp.exec('\/Date(1330848000000)\/')
["/Date(1330848000000)/","1330848000000", undefined]

regExp.exec('\/Date(1)\/')
["/Date(1)/","1", undefined]

regExp.exec('\/Date(1330848000000-)\/')
null

regExp.exec('/Date(1330848000000-0800)\/')
["/Date(1330848000000-0800)/","1330848000000","0800"]

regExp.exec('\/Date(1330848000000-0800)/')
["/Date(1330848000000-0800)/","1330848000000","0800"]

regExp.exec('\/date(1330848000000-0800)\/')
null

regExp.exec('\/Date(1aaa848000000-0800)\/')
null

regExp.exec('\/Date(1330848000000-0a00)\/')
null