Javascript regex to parse .net json Datetime
I am not a regex guru, so I am asking for help coming up with a regex that will work like this:
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
I got stuck pretty early with something as silly as this:
/\\bla(.*)bla/.exec('\bla123bla') = null // instead of [ ..., '123']
new RegExp('\\\\bla(.*)bla').exec('\bla123bla') = null // instead of [ ..., '123']
source to share
You can use this regex if the string never contains any numbers other than time and timezone:
/(\d+)(?:-(\d+))?/
Putting in code:
var regex = /(\d+)(?:-(\d+))?/;
// regex.exec...
If you really need to check and extract numbers from a string:
/^\/Date\((\d+)(?:-(\d+))?\)\/$/
The regex above checks if the string matches the exact form and also extracts numbers.
source to share
The following regular expression checks your required constraints:
\\/Date\((\d{13})(-(\d{4}))?\)\\/
It checks for presence \
, /
followed by text Date
, followed by parentheses containing 13 digits and an optional sequence -
, followed by 4 digits, then the required \
and /
.
\\
matches a single \
, which requires escaping as it is a special character in the regular expression. The same happens in the case of (
and )
.
Of this number, $ 1 matches 13 digits inside the brackets, and $ 3 matches 4 digits if present.
source to share
I kept playing with regexes and finally got it
Trasable slashes are just ignored by javascript, so this is the solution I came out with (tested on chrome console)
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
source to share