Reputation: 2546
I have this Reg. Expression
value.match(/^\/Date\(\d*[\+\-]?\d*\)\/$/))
that I use to find dates like this example
/Date(2208988800000+0100)/
For reason that I can't understand when I have a date with a negative value of milliseconds (previous of Jan 1st 1970) regex does not work.
/Date(-2208988800000+0100)/
Any suggestions?
Upvotes: 3
Views: 271
Reputation: 3455
A regular expression looks for the form and your form is right now:
/
"Date" literally
(
zero or unlimited digets
a plus or minus character
zero or unlimited digets
closing brackets
/
You are missing the minus sign:
^\/Date\(\-?\d+[\+\-]?\d+\)\/$
The ?
is a so called quantifier and means 1 or 0 times.
Further reading:
regex101.com is a nice playground for testing your regular expression in real time. Use it and profit from the "quick reference" on the bottom.
Upvotes: 1
Reputation: 1075189
The problem is your regex doesn't allow for the minus sign on the number (dates prior to 1970 have negative time values, since the time values are offsets in milliseconds from Jan 1st 1970 at midnight). You need to add -?
at the beginning:
value.match(/^\/Date\(-?\d*[\+\-]?\d*\)\/$/))
// Here --------------^^
var value = "/Date(-2208988800000+0100)/";
console.log(value.match(/^\/Date\(-?\d*[\+\-]?\d*\)\/$/));
Side note: I think both of your \d*
s want to be \d+
s. You want at least one digit on either side of the +
/-
separating the timezone offset...
Side note 2: In [\+\-]
, neither backslash is actually required. +
isn't special within []
, and -
is only special within []
when it's not at the beginning or end.
Upvotes: 4
Reputation: 1702
Your regular expression says:
/Date( at the beginning followed by
0 or more digits followed by
+ or - sign followed by
0 or more digits followed by
)/ at the end
The input "/Date(-2208988800000+0100)/"
matches
/Date( at the beginning followed by
0 or more digits followed by
+ or - sign followed by
0 or more digits
but then the next thing is the "+" in front of "0100". Thus, the match fails.
The reg exp you want is probably
/^\/Date\([\+\-]*\d*[\+\-]?\d*\)\/$/)
Upvotes: 1